死锁

来源:互联网 发布:com口测试软件 编辑:程序博客网 时间:2024/06/01 20:57

死锁的代码演示

public class DeadLockDemo {    private static String A = "A";    private static String B = "B";    public static void main(String[] args) {        new DeadLockDemo().deadLock();    }    private void deadLock() {        Thread th1 = new Thread(new Runnable(){            @Override            public void run() {                synchronized (A) {                    try {                        Thread.currentThread().sleep(2000);                    } catch (InterruptedException e) {                        // TODO Auto-generated catch block                        e.printStackTrace();                    }                    synchronized (B) {                        System.out.println("1");                    }                }            }        });        Thread th2 = new Thread(new Runnable() {            @Override            public void run() {                synchronized (B) {                    synchronized (A) {                        System.out.println("2");                    }                }            }        });        th1.start();th2.start();    }}