java - 多线程死锁测试
阿神
阿神 2017-04-18 10:54:48
0
3
683
package test;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * Created by rhwayfun on 16-4-3.
 */
public class ThreadTest {

    private static DateFormat format = new SimpleDateFormat("HH:mm:ss");

    public synchronized void tryOther(ThreadTest other) throws InterruptedException {
        System.out.println(Thread.currentThread().getName() + " enter tryOther method at " + format.format(new Date()));      
        System.out.println(Thread.currentThread().getName() + " tryOther method is about to invoke other method at " + format.format(new Date()));
        other.other();
    }

    public synchronized void other() throws InterruptedException {
        System.out.println(Thread.currentThread().getName() + " enter other method atatatatat " + format.format(new Date()));
    }

    public static void main(String[] args) throws InterruptedException {
        final ThreadTest d1 = new ThreadTest();
        final ThreadTest d2 = new ThreadTest();

        Thread t1 = new Thread(new Runnable() {
            public void run() {
                try {
                    d1.tryOther(d2);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "threadA");

        Thread t2 = new Thread(new Runnable() {
            public void run() {
                try {
                    d2.tryOther(d1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "threadB");

        t1.start();
        //让threadA先运行一秒
        TimeUnit.SECONDS.sleep(1);
        t2.start();

    }
}

如上,随便找的产生死锁的代码,问题:
TimeUnit.SECONDS.sleep(1);加上这行后,不存在死锁问题。sleep并不释放锁,为何这边死锁情况会消失。
输出结果为:
threadA enter tryOther method at 15:37:39
threadA tryOther method is about to invoke other method at 15:37:39
threadA enter other method atatatatat 15:37:39
threadB enter tryOther method at 15:37:40
threadB tryOther method is about to invoke other method at 15:37:40
threadB enter other method atatatatat 15:37:40

注掉这行,正常死锁。
输出结果为:
threadB enter tryOther method at 15:37:10
threadA enter tryOther method at 15:37:10
threadB tryOther method is about to invoke other method at 15:37:10
threadA tryOther method is about to invoke other method at 15:37:10

阿神
阿神

闭关修行中......

全部回覆(3)
大家讲道理

線程A拿到tryOther鎖但是他還要得到other的鎖
線程B拿到tryOther的鎖但是他還要拿到other的鎖
有可能A剛剛釋放鎖B也剛剛釋放tryOther的鎖.
此時但他們同時都想要取得other的鎖此時誰也不讓誰發生死鎖
解決方法讓兩個線程不要同時去搶第二把鎖.讓A停一會
但是如果你把時間調成納秒級多次嘗試也會發生死鎖
不建議這樣預防死鎖.如果並發量高的情況下.

阿神

雙方在爭同一把鎖,不會死鎖啊

PHPzhong

自己突然知道為什麼了,懶得刪帖了。寫下我的看法,如果有錯,歡迎指正,輕噴
在沒有sleep時,a線程啟動,完成tryOther方法,釋放鎖並去執行other方法,此時b獲得鎖執行tryOther方法,
此時a在other方法中所需資源被b執行緒鎖住,b執行完tryOther後需要取得a資源,由此產生死鎖。

加上sleep後。在a執行tryOther方法釋放鎖,此時b執行緒並沒有執行,此時順利取得other鎖。 2s後b線程執行,
無死鎖環境。

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!