java多線程之模擬死鎖

<span style="font-size:14px;">package thread;  

  

public class TestDeadLock implements Runnable{  

    public int flag = 1;  

    static Object o1 = new Object(),o2 = new Object();  

      

    @Override  

    public void run() {  

        System.out.println("flag:"+flag);  

        if(flag==1){  

            synchronized(o1){  

                try {  

                    Thread.sleep(100);  

                } catch (InterruptedException e) {  

                    // TODO Auto-generated catch block  

                    e.printStackTrace();  

                }  

                synchronized(o2){  

                    System.out.println("我是o2,被鎖住了");  

                }  

            }  

        }  

        if(flag==0){  

            synchronized(o2){  

                try {  

                    Thread.sleep(100);  

                } catch (InterruptedException e) {  

                    // TODO Auto-generated catch block  

                    e.printStackTrace();  

                }  

                synchronized(o1){  

                    System.out.println("我是o1,被鎖住了");  

                }  

            }  

        }  

          

    }  

  

    public static void main(String[] args) {  

        // TODO Auto-generated method stub  

        TestDeadLock d1 = new TestDeadLock();  

        TestDeadLock d2 = new TestDeadLock();  

        Thread t1 = new Thread(d1);  

        Thread t2 = new Thread(d2);  

        d1.flag = 1;  

        d2.flag = 0;  

        t1.start();  

        t2.start();  

    }  

}  

</span>  

運行結果爲

flag:1
flag:0

由於發生死鎖,兩條if語句中的打印語句永遠都不會執行


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章