2012-09-15 25 views
0

我已經做了我自己的小併發框架(只是爲了學習目的)由java.util.concurrency包啓發。這是關於Callable/Future機制的。我的下面的代碼是完整的,可編譯並且很容易理解。同步的問題:我想主線程到另一個線程之前運行,但它有時doesn't

我的問題是,有時我碰上了僵局,其中第一線程(main thread)等待從其他線程的信號。但是在主線程進入等待狀態之前,另一個線程已經通知主線程,所以主線程不能喚醒。

FutureTask.get()應該總是前FutureTask.run()運行但有時run()方法(這是由new thread調用)的get()方法(這是由main thread調用)之前運行。我不知道如何防止這種情況。

這是我多麼希望兩個線程來運行一個僞代碼。

//From main thread: 
Executor.submit().get() (in get() the main thread waits for new thread to notify) 
     ->submit() calls Executor.execute(FutureTask object) 
            -> execute() starts new thread 
               -> new thread shall notify `main thread` 

我無法理解的新線程如何啓動和運行比實際啓動新線程的主線程更快。

回答

2

condition.await();檢查,如果結果已經設置。

+0

那麼容易! :-D謝謝! – Rox