java模拟死锁事故现场

package test;
import org.junit.Test;


public class DeadLock {
public static void main(String[] args) {
Mythread2 th=new Mythread2();
Thread thread=new Thread(th);

thread.start();
try {Thread.sleep(10);} catch (Exception e) {} //确保fun()在thread.start()后执行
th.fun();
}
}
class Mythread2 implements Runnable{
public Object object=new Object();


public void run(){
synchronized (object) { //同步代码块, Object对象锁
try {Thread.sleep(30);} catch (Exception e) {}
System.out.println("lock location");
//*死锁位置*,object对象锁与Mythread2对象锁互相等待
fun();
}
}

public synchronized void fun(){ //同步方法, Mythread锁
synchronized (object) {
System.out.println("function");
}
}
}


//无死锁结果:function locklocation function  
//死锁结果: locklocation
//过程:thread线程开启->thread获取到Object对象锁->thread睡眠30ms->主线程睡10ms
//->主线程进入fun方法->主线程获取到Mythread2对象锁->主线程准备获取Object对象锁进入代码块
//->主线程等待Mythread2释放Object锁(等待1)->thread线程睡眠结束->thread线程打印code
//->thread线程准备获取Mythread2对象锁进入fun方法
//->thread线程等待主线程释放Mythread2对象锁(等待2)

猜你喜欢

转载自blog.csdn.net/fw6669998/article/details/54619036