线程死锁-死锁产生演练

线程死锁

线程死锁-死锁产生演练_第1张图片
代码演练demo:

package cn.yb.thread;

public class DeadLockRunnable implements Runnable {
     
    private int flag;//决定线程走向的标记
    private static Object obj1 = new Object();//锁对象1
    private static Object obj2 = new Object();//锁对象2
    
    public DeadLockRunnable(int flag) {
     
    	this.flag = flag;
    }
    
	public void run() {
     
		if(flag == 1){
     
		 //线程1执行代码	
		  synchronized (obj1) {
     
			System.out.println(Thread.currentThread().getName()+"已经获取到资源obj1,请求obj2");
			try {
     
				Thread.sleep(1000);
			} catch (InterruptedException e) {
     
				e.printStackTrace();
			}
			synchronized (obj2) {
     
				System.out.println(Thread.currentThread().getName()+"已经获取到obj1和obj2");
			}
		 }	
		}else {
     
	     //线程2执行代码	
			  synchronized (obj2) {
     
					System.out.println(Thread.currentThread().getName()+"已经获取到资源obj2,请求obj1");
					try {
     
						Thread.sleep(1000);
					} catch (InterruptedException e) {
     
						e.printStackTrace();
					}
					synchronized (obj1) {
     
						System.out.println(Thread.currentThread().getName()+"已经获取到obj1和obj2");
					}
				 }	
		}
	}

}

测试类:

package cn.yb.thread;

public class DeadLockDemo {
     

	public static void main(String[] args) {
     
		//1.创建两个DeadLockRunnable实例:flag = 1;flag = 2
		DeadLockRunnable runnable1 = new DeadLockRunnable(1);
		DeadLockRunnable runnable2 = new DeadLockRunnable(2);
		//2.创建两个线程执行两个DeadLockRunnable
		Thread thread1 = new Thread(runnable1,"runnable1");
		Thread thread2 = new Thread(runnable2,"runnable2");
		thread1.start();
		thread2.start();
		
	}

}

运行结果:
线程死锁-死锁产生演练_第2张图片

你可能感兴趣的:(线程死锁-死锁产生演练,thread,java,多线程,并发编程)