线程学习(四) 死锁简单实现

来源:互联网 发布:mac lion 下载 编辑:程序博客网 时间:2024/05/17 04:04
//以下程序简单演示形成死锁public class TestDeadLock implements Runnable {public int flg=1;static Object o1=new Object(),o2=new Object();public void run(){System.out.println("flg="+flg);if(flg==1){synchronized(o1){try{Thread.sleep(500);}catch(Exception e){e.printStackTrace();}synchronized(o2){System.out.println("1");}}}else if(flg==0){synchronized(o2){try{Thread.sleep(500);}catch(Exception e){e.printStackTrace();}synchronized(o1){System.out.println("0");}}}}public static void main(String[] args){TestDeadLock td1=new TestDeadLock();TestDeadLock td2=new TestDeadLock();td1.flg=0;td2.flg=1;Thread t1=new Thread(td1);Thread t2=new Thread(td2);t1.start();t2.start();}}


运行结果截图:

0 0
原创粉丝点击