例子中:
conditionfactory類所在包路徑:
conditionfactory類是一個condition工廠,with()會建立一個conditionfactory執行個體:
conditionfactory帶參構造函數如下:
構造函數的參數值:
通過這些參數可知,預設的逾時時間為10s, 輪詢間隔為100ms;
通過conditionfactory的成員方法,對成員變量進行替換,比如atmost(60, seconds):
将final成員變量this.timeoutconstraint替換成使用者設定的new duration(60, seconds);
<code>and()</code>傳回this;
當使用者再設定<code>pollinterval(one_hundred_milliseconds)</code>時:
會重新new一個對象,one_hundred_milliseconds會賦給final成員變量:pollinterval,之前賦過的值保留,比如:timeoutconstraint還是上一步設定的new duration(60, seconds);依次類推new duration(50, milliseconds)賦給final成員變量:polldelay; "count is greater 6"賦給final成員變量:alias。
最終執行個體化的conditionfactory對象中,成員變量為:
contiditionfactory類成員方法until():
generateconditionsettings()将conditionfactory的final變量指派給javabean對象conditionsettings:
執行個體化callablecondition類,構造函數:
同時執行個體化conditionawaiter對象,conditionawaiter構造函數:
并調用callablecondition執行個體的await()方法:
接着調用conditionawaiter執行個體的await():
conditionawaiter類中有個countdownlatch成員變量:
執行個體化時,定義了:
countdownlatch:
在conditionawaiter執行個體的await()方法中,建立了一個輪詢線程:
其中while循環中:
<code>future<?> future = executor.submit(new conditionpoller(pollinterval));</code>
線程執行體:
具體執行:conditionevaluationresult result = conditionevaluator.eval(delayed);
執行個體化conditionawaiter時傳入conditionevaluator的實作類conditionevaluationwrapper;
conditionevaluationwrapper中eval()方法:
其中:
<code>boolean conditionfulfilled = matcher.call();</code>
call()傳回computed result。
matcher執行個體在conditionevaluationwrapper構造函數中執行個體化:
本例為:
如果異步執行結果滿足,latch.countdown();
使latch.getcount() == 0,導緻while循環break中斷;
否則,異步執行結果不滿足,每次while循環sleep:
while循環每次将eval()送出給線程池;如果是duration.forever一直等待執行結束;否則,最多等待maxtimeout檢視執行結果。
建立輪詢線程後,判斷latch是否為0,如果不為0,線程阻塞;
最後根據finishedbeforetimeout為false,拼接提示語。
錯誤提示語:
定義countdownlatch變量latch,并初始化為<code>new countdownlatch(1)</code>;
啟動一個輪詢線程,該輪詢線程執行體中實作了while循環,每次先判斷latch.getcount()是否為0,如果為0,跳出while循環;否則,将判斷異步結果是否成功的任務送出給線程池executor執行,執行體會判斷是否成功,成功則latch.countdown()(導緻latch.getcount()為0,下次跳出while循環);同時,每次while循環執行 <code>thread.sleep(pollinterval.getvalueinms());</code> 如果輪詢線程執行體while循環一直不滿足條件,主線程将阻塞maxtimeoutunit:<code>latch.await(maxtimeout, maxtimeoutunit)</code>, 如果latch.getcount()不為0,即異步校驗不成功,finishedbeforetimeout置為false, <code>finishedbeforetimeout = latch.await(maxtimeout, maxtimeoutunit)</code>, 輸出異常資訊。