使用Synchronized 模拟死锁产生的示例

使用synchronized可以为资源加锁,保证共享资源访问的同步安全问题。不恰当的使用将会导致死锁问题。

public class DeadLockTest {
    public static String lock1 = "lock1";
    public static String lock2 = "lock2";
    public static void main(String[] args){
        Thread a = new Thread(new Lock1());
        Thread b = new Thread(new Lock2());
        a.start();
        b.start();
    }
}
class Lock1 implements Runnable{
    @Override
    public void run(){
        try{
            while(true){
            	System.out.println(Thread.currentThread().getName()+" want to get lock1");
                synchronized(DeadLockTest.lock1){
                    System.out.println(Thread.currentThread().getName()+" get lock1");
                    Thread.sleep(100);
                    synchronized(DeadLockTest.lock2){
                        System.out.println(Thread.currentThread().getName()+" get lock2");
                    }
                }
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}
class Lock2 implements Runnable{
    @Override
    public void run(){
        try{
            while(true){
            	System.out.println(Thread.currentThread().getName()+" want to get lock2");
                synchronized(DeadLockTest.lock2){
                    System.out.println(Thread.currentThread().getName()+" get lock2");
                    Thread.sleep(100);
                    synchronized(DeadLockTest.lock1){
                        System.out.println(Thread.currentThread().getName()+" get lock1");
                    }
                }
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}

控制台如下信息

找到目录下 cmd下运行 jps


此时进程号为5944,输入 jstack 5944



发现有死锁信息的提示。

猜你喜欢

转载自blog.csdn.net/zclworld/article/details/79760328