JAVA基础(多线程死锁)

1,死锁

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

  • 尽量不要嵌套使用

public class Demo5_DeadLock {

    private static String s1 = "筷子左";

    private static String s2 = "筷子右";

    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(s2) {

                        System.out.println(getName() + "...获取" + s2 + "等待" + s1);

                        synchronized(s1) {

                            System.out.println(getName() + "...拿到" + s1 + "开吃");

                        }

                    }

                }

            }

        }.start();

    }

}



 

你可能感兴趣的:(JAVA基础,JAVA基础)