首页 > 其他 > 详细

死锁的例子 代码练习

时间:2019-10-04 18:47:14      阅读:57      评论:0      收藏:0      [点我收藏+]
/**
 * 死锁
 * 两个线程同时运行了,线程1中s1拿到了s2的锁  线程2中s2要拿s1的锁。就僵持住了,程序无法继续运行
 */
public class TestDeadLock {
    public static void main(String[] args) {
        final  StringBuffer s1 = new StringBuffer();
        final  StringBuffer s2 = new StringBuffer();

        new Thread(){
            public  void run(){
                synchronized (s1){
                    s2.append("a");
                    try {
                        Thread.sleep(20);
                    }catch (InterruptedException e){
                        e.printStackTrace();
                    }
                    synchronized (s2){
                        s1.append("b");
                        System.out.print(s1);
                        System.out.print(s2);
                    }
                }
            }
        }.start();

        new Thread(){
            public  void run(){
                synchronized (s2){
                    s1.append("c");
                    try {
                        Thread.sleep(20);
                    }catch (InterruptedException e){
                        e.printStackTrace();
                    }
                    synchronized (s1){
                        s1.append("d");
                        System.out.print(s1);
                        System.out.print(s2);
                    }
                }
            }
        }.start();
    }
}

死锁的例子 代码练习

原文:https://www.cnblogs.com/liyao0312/p/11622696.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!