我有一個線程執行一些計算,每個計算都有一個id。 每個計算都會啓動一個新線程。 當處理完成時,數據被寫入與其ID相對應的數據庫中。當另一個線程可能存在或不存在時線程同步
有可能(也可能不是)另一個請求,這需要從另一個線程計算結果。 它在數據庫中查找id,如果發現它會返回結果。 如果不是,則需要檢查計算是否已在進行中 如果是,則等待計算完成。喚醒完成後,從數據庫獲取數據並返回。 如果沒有正在運行的計算,則開始計算並等待。喚醒完成後,從數據庫獲取數據並返回。
The pseudo code is as follow:
CalculationClass
receive a request id from a Consumer
add id to CalculatingIds List
when calculated
write data to DB
remove id from CalculatingIds List
GetDataClass
look for the the result corresponding to id
if found return data
else check if the id is present in the CalculatingIds List
if present, wait and wake up when data is available
if not present, pass the id to the Consumer Queue. Wait and wake up when data is available
我不能找到一種方法,在2個線程的情況下,當數據還沒有準備好GetDataClass同步。我正在考慮爲每個計算創建一個新對象,然後使用它來同步2個線程。
synchronize(lock)
if(noData && calculationRunning)
lock.wait();
else
queue.add(id)
CalculatingIds.add(id)
但是,在CalculationClass
的情況下,我將如何處理此鎖? 當GetDataClass
線程不存在時,我將如何處理該案例?
恐怕我不完全理解它。所以你想要我鎖定藏品?但那我該如何通知並等待呢?你能否詳細解釋一下。 – rd22
你知道如何使用'notifyAll'和'wait'等函數嗎?如果沒有,你還沒有準備好做這樣的事情。開始[這裏](http://howtodoinjava.com/core-java/multi-threading/how-to-work-with-wait-notify-and-notifyall-in-java/)。 (在保持等待或通知的共享狀態的鎖的同時,同時調用'notifyAll'和'wait'是非常正常的。) –
實際上,你幾乎把它與你的僞代碼一起使用。你瞭解僞代碼嗎? –