zoukankan      html  css  js  c++  java
  • 死锁的例子 代码练习

    /**
     * 死锁
     * 两个线程同时运行了,线程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();
        }
    }
    
    
  • 相关阅读:
    团购网站之大众点评
    cas xml
    smsUtil
    solr配置
    xml
    yu
    Schema.xml
    ApplicationContext-redis.xml
    fast
    第一版
  • 原文地址:https://www.cnblogs.com/liyao0312/p/11622696.html
Copyright © 2011-2022 走看看