死锁

例子

package com.test.demo;

/**
 * Created by admin on 2017/6/12 10:00.
 */
public class DemoThread implements Runnable {
    /**
     * 被锁的对象要是同一个对象,即被 static 修饰,
     * 全局共享对象,不然多线程中 object1,object2 new出来的不是同一对象
     */
    static Object object1 = new Object();
    static Object object2 = new Object();
    boolean flag;

    DemoThread(boolean flag) {
        this.flag = flag;
    }

    @Override
    public void run() {
        if (flag) {
            synchronized (object1) {
                System.out.println("if object1 adress:" + Integer.toHexString(object1.hashCode()));
                synchronized (object2) {
                    System.out.println("if object2 adress:" + Integer.toHexString(object2.hashCode()));
                }
            }
        } else {
            synchronized (object2) {
                System.out.println("else object2 adress:" + Integer.toHexString(object2.hashCode()));
                synchronized (object1) {
                    System.out.println("else object1 adress:" + Integer.toHexString(object1.hashCode()));
                }
            }
        }
    }

    public static void main(String[] args) {
        Thread t1 = new Thread(new DemoThread(true));
        Thread t2 = new Thread(new DemoThread(false));
        t1.start();
        try {
            Thread.sleep(5);
        } catch (Exception e) {

        }
        t2.start();
    }

}

 

posted on 2017-06-12 10:23  流年染指了悲伤  阅读(155)  评论(0编辑  收藏  举报