java 死锁两种实现

synchronized实现的死锁代码:

package net.flyingfat.lock;

public class DeadLock {

	private String lockA="A";
	
	private String lockB="B";
	
	public static void main(String[] args) {
		
		final DeadLock deadLock=new DeadLock();

		new Thread(new Runnable() {
			public void run() {
				try {
					deadLock.run1();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}).start();
		
		
		new Thread(new Runnable() {
			public void run() {
				try {
					deadLock.run2();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}).start();
		
	}
	
    public void run1() throws Exception{
    	
    	synchronized (lockA) {
    		Thread.sleep(1000);
    		System.out.println("run1 get lockA");
    		synchronized (lockB) {
    			System.out.println("run1 get lockB");
    		}
		}
    }	
    
    public void run2() throws Exception{
    	
    	synchronized (lockB) {
    		Thread.sleep(1000);
    		System.out.println("run2 get lockB");
        	synchronized (lockA) {
        		System.out.println("run2 get lockA");
    		}
		}
    	
    }	

}

ReentrantLock实现的死锁代码:

package net.flyingfat.lock;

import java.util.concurrent.locks.ReentrantLock;

public class DeadLock2 {
	public static void main(String[] args) {
		final DeadLock2 deadLock2=new DeadLock2();
		final ReentrantLock lock1=new ReentrantLock();
		final ReentrantLock lock2=new ReentrantLock();
		new Thread(new Runnable() {
			public void run() {
				try {
					deadLock2.run(lock1,lock2);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}).start();
		
		new Thread(new Runnable() {
			public void run() {
				try {
					deadLock2.run(lock2,lock1);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}).start();
	}
	
    public void run(ReentrantLock lockA,ReentrantLock lockB) throws Exception{
    	try{
    		lockA.lock();
			try{
				Thread.sleep(1000);
	    		lockB.lock();
			}catch(Exception e){
	    		e.printStackTrace();
	    	}finally{
	    		lockB.unlock();
	    	}
    	}catch(Exception e){
    		e.printStackTrace();
    	}finally{
    		lockA.unlock();
    	}
    }	

}

java 死锁的检测可以通过jconsole线程检测出来,截图如下:

java 死锁两种实现_第1张图片

解决死锁的最关键还是尽量避免单个线程去获取多个锁资源。

你可能感兴趣的:(java,死锁)