线程-模拟死锁问题

来源:互联网 发布:ubuntu Server安装教程 编辑:程序博客网 时间:2024/04/29 15:22
public class DeadLockTest implements Runnable{    private int flag;    public DeadLockTest(int flag){        this.flag = flag;     }    static Object o1 = new Object(),o2 = new Object();    @Override    public void run() {        if(flag == 1) {            synchronized(o1) {                try {                    System.out.println(Thread.currentThread().getName() + " 占据o1");                    Thread.sleep(100);                } catch (InterruptedException e) {                    e.printStackTrace();                }                 System.out.println(Thread.currentThread().getName() + " 等待t2释放o2");                synchronized(o2) {                    System.out.println("flag == 1");                }            }        }        if(flag == 2) {            synchronized(o2) {                try {                    System.out.println(Thread.currentThread().getName() + " 占据o2");                    Thread.sleep(100);                } catch (InterruptedException e) {                    e.printStackTrace();                }                 System.out.println(Thread.currentThread().getName() + " 等待t1释放o1");                synchronized(o1) {                    System.out.println("flag == 2");                }            }        }        // 上面2个线程死锁 执行不到此处        System.out.println("ok");    }    public static void main(String[] args) {        Thread t1 = new Thread(new DeadLockTest(1), "t1");        Thread t2 = new Thread(new DeadLockTest(2), "t2");        t1.start();        t2.start();    }}
0 0
原创粉丝点击