快捷导航

为什么这样写无法产生死锁

public class DeadLockTest {    public static Integer s1 = 1;    public static Integer s2 = 1;    public static void main (String args[]){        DeadLockThread1 d1 = new DeadLockThread1();        d1.start();        DeadLockThread2 d2 = new DeadLockThread2();        d2.start();    }}class DeadLockThread1  extends Thread {    public void run() {        synchronized (DeadLockTest.s1){            try {                Thread.sleep(3000);            } catch (InterruptedException e) {                e.printStackTrace();            }            synchronized (DeadLockTest.s2) {                System.out.println(Thread.currentThread().getName()+" is running");            }        }    }}class DeadLockThread2 extends Thread {    public void run() {        synchronized (DeadLockTest.s2){            try {                Thread.sleep(3000);            } catch (InterruptedException e) {                e.printStackTrace();            }            synchronized (DeadLockTest.s1) {                System.out.println(Thread.currentThread().getName()+" is running");            }        }    }}

但是如果将DeadLockTest类中的两个静态变量改为不同的值,就能产生死锁,这是为什么?

免责声明:本内容仅代表回答者见解不代表本站观点,请谨慎对待。

版权声明:作者保留权利,不代表本站立场。

回复

使用道具 举报

参与会员1

synchronized关键字啊
数字相同,表示两者都有钥匙
数字不同,表示钥匙你需要我的钥匙,我也需要你的钥匙,所以就死了
回复

使用道具 举报

可能感兴趣的问答

发新帖
  • 微信访问
  • 手机APP