Java_基础—多线程(死锁)

多线程同步的时候, 如果同步代码嵌套, 使用相同锁, 就有可能出现死锁

为了避免“死锁”的问题出现,尽量不要使用嵌套

死锁举例:

package com.soar.syn;

public class Demo5_DeadLock {

    private static String s1 = "锁A";
    private static String s2 = "锁B";

    public static void main(String[] args) {

        new Thread(){
            public void run(){
                    while(true){
                        synchronized(s1){
                        System.out.println(getName()+"获取" + s1 + "等待" + s2);
                        synchronized(s2){
                            System.out.println(getName()+"获得" + s2 + "哈哈");
                        }
                    }
                }
            }
        }.start();


        new Thread(){
            public void run(){
                    while(true){
                        synchronized(s1){
                        System.out.println(getName()+"获取" + s2 + "等待" + s1);
                        synchronized(s2){
                            System.out.println(getName()+"获得" + s1 + "哈哈");
                        }
                    }
                }
            }
        }.start();
    }

}
posted @ 2017-09-02 19:54  Soar_Sir  阅读(102)  评论(0编辑  收藏  举报