模拟死锁

public class A {

    public void a() {
        System.out.println(Thread.currentThread().getName() + " in a.");
    }

}

 

public class B {

    public void b() {
        System.out.println(Thread.currentThread().getName() + " in b.");
    }

}

 

/**
 * 模拟死锁
 */
public class TestDeadLock {

    /*
     * 死锁的解决办法:
     * 对象的加锁顺序一定要一致,比如都是先加a的锁,后加b的锁.
     */

    public static void main(String[] args) {

        // 两个对象
        A a = new A();
        B b = new B();

        /*
         * a和b的方法必须同步执行(例如A账户转账给B账户)
         * 所以a和b的方法执行之前,要要对a对象和b对象都加锁
         * 
         * 模拟:
         * 线程1先给a加锁,给b加锁的时候失败,等待线程2释放b的锁。
         * 线程2先给b加锁,给a加锁的时候失败,等待线程1释放a的锁。
         */

        // 线程1
        new Thread(new Runnable() {
            @Override
            public void run() {
                // 先锁a
                synchronized (a) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    // 1s后去锁b
                    synchronized (b) {
                        a.a();
                        b.b();
                    }
                }

                System.out.println(Thread.currentThread().getName() + " done.");
            }
        }).start();

        // 线程2
        new Thread(new Runnable() {
            @Override
            public void run() {
                // 先锁b
                synchronized (b) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    // 1s后去锁a
                    synchronized (a) {
                        b.b();
                        a.a();
                    }

                }

                System.out.println(Thread.currentThread().getName() + " done.");
            }
        }).start();

    }

}

 

posted @ 2018-05-30 18:12  迷失之路  阅读(296)  评论(0编辑  收藏  举报