Java死锁程序

来源:互联网 发布:手机游戏 知乎 编辑:程序博客网 时间:2024/06/09 15:17
import java.io.*;public class TestDeadLock implements Runnable{public int flag = 0;static Object o1 = new Object(), o2 = new Object();public void run(){System.out.println("flag="+flag);if(flag==1){synchronized (o1){try{Thread.sleep(500);}catch(Exception e){e.printStackTrace();}synchronized (o2){System.out.println("Lock o1 first and flag = 1");}}}if(flag==0){synchronized (o2){try{Thread.sleep(500);}catch(Exception e){e.printStackTrace();}synchronized (o1){System.out.println("Lock o2 first and flag = 0");}}}} public static void  main(String[] args){ TestDeadLock lock1 = new TestDeadLock();TestDeadLock lock2 = new TestDeadLock();lock1.flag = 1;lock2.flag = 0;Thread t1 = new Thread(lock1);Thread t2 = new Thread(lock2);t1.start();    t2.start();}}

原创粉丝点击