Java实现一个死锁

Java实现一个死锁

有一个藏宝图(treasureMapFragment)分成两份jack持有treasureMapFragment1残片1,json持有残片2。jack要求必须先看到json的残图才给json看自己的残图,而json要求必须先看到jack的残图才给jack看自己的残图。双方都在请求对方持有的资源但是不释放自己手里的资源,就形成了死锁。

package yu;

public class DeadLock {
    public static void main(String[] args) {
        Object treasureMapFragment1 = new Object();
        Object treasureMapFragment2 = new Object();
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (treasureMapFragment1) {
                    String name = Thread.currentThread().getName();
                    System.out.println(name + "持有藏宝图碎片1");
                    try {
                        Thread.currentThread().sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    synchronized (treasureMapFragment2) {
                        System.out.println(name + "同时也获得了藏宝图碎片2");
                    }
                }
            }
        });
        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (treasureMapFragment2) {
                    String name = Thread.currentThread().getName();
                    System.out.println(name + "持有藏宝图碎片2");
                    try {
                        Thread.currentThread().sleep(200);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    synchronized (treasureMapFragment1) {
                        System.out.println(name + "同时也获得了藏宝图碎片1");
                    }

                }
            }
        });
        t1.setName("jack");
        t2.setName("json");
        t1.start();
        t2.start();
    }
}
posted @ 2021-08-23 16:12  aixueforever  阅读(627)  评论(0编辑  收藏  举报