我正在嘗試編寫一個監視阻止操作需要多長時間的線程。例如,我有一個阻擊戰是這樣的:監視阻止操作
class BlockingThread extends Thread{
public volatile boolean success = false;
public volatile long startedTime = 0;
public void run(){
startedTime = System.currentTimeMillis();
success = doBlockingAction(); //no idea how long this action will take
}
}
,我希望有另一個線程基本上都會叫「超時」功能,如果阻擊戰時間過長:
class MonitorThread extends Thread{
public void run(){
while(System.currentTimeMillis() - blockingThread.startedTime > TIMEOUT_DURATION)
{
..keep waiting until the time runs out..
}
if(!blockingThread.success){
listener.timeout();
//Took too long.
}
}
}
我無法理解如何確保BlockingThread實際上處於阻塞操作中,而我正在測量MonitorThread中的時間。
如果我做這樣的事情,
Thread blockingThread = new BlockingThread();
blockingThread.start();
Thread monitorThread = new MonitorThread();
monitorThread.start();
也不能保證一個線程實際開始運行之前,其他的代碼,所以我現在有沒有辦法知道,如果我的超時線程實際上正確測量阻止行爲的時間。我假設答案與鎖定和wait
ing有關,但我無法弄清楚。
我希望你的意思是'類BlockingThread'和'類MonitorThread'。 – Jeffrey
SO上有一個[question](http://stackoverflow.com/q/2275443/960195)專門用於超時方法執行。這可能會有所幫助。 –
@Jeffrey哈哈,哎呀。謝謝你的收穫。 – you786