[英]Future.cancel and ReentrantLocks
設想
我有這個 class,比如說Foo
,它的唯一工作是順序執行一組任務。 聽起來很簡單,對吧? 好吧,所有這些任務都在各自獨立的線程中執行。 它不是簡單地在每個任務上調用Thread.join()
來確保順序執行,而是使用ReentrantLock
和Condition
。 例如,
public class Foo
{
private final Lock lock;
private final Condition condition;
private Future<?> task;
public Foo()
{
lock = new ReentrantLock();
condition = lock.newCondition();
run();
}
/**
* Runs Foo
*/
public void run()
{
Runnable runnable = new Runnable()
{
@Override
public void run()
{
lock.lock();
try
{
// do tasks
}
finally
{
lock.unlock();
}
}
};
// Submit task
task = Executors.newSingleThreadExecutor().submit(runnable);
}
/**
* Blocks execution until signal is received
*/
public void waitForNotification()
{
try
{
condition.await();
}
catch (InterruptedException e)
{
}
}
/**
* Gets the lock
*
* @return Lock
*/
public final Lock getLock()
{
return lock;
}
/**
* Gets the condition
*
* @return Condition
*/
public final Condition getCondition()
{
return condition;
}
/**
* Gets the sender's task
*
* @return Task
*/
public Future<?> getTask()
{
return task;
}
}
在每個任務之后, waitForNotification()
並等待另一個 class,比如說Bar
來喚醒它。 Bar
的唯一工作是處理通知應用程序任務是通過還是失敗的響應。 話雖如此,它將做以下兩件事之一:
getTask().cancel
)getCondition().signal
)第 2 項工作得很好,但第 1 項不行。 例如,
public class Bar
{
private Foo foo;
// doesn't work!
public void handleFailed()
{
// Cancel task
foo.getTask().cancel(true)
}
public void handlePassed()
{
// Signal waiting Foo
foo.getLock().lock();
try
{
foo.getCondition().signal();
}
finally
{
foo.getLock().unlock();
}
}
}
而不是取消線程,它似乎只是中斷了它,這導致Foo
繼續執行。 抱歉冗長,但我想給你們一個清晰的畫面。 有什么建議么?
除非任務在中斷時停止,否則標志將被設置並保持設置,直到任務結束或決定停止。
http://www.google.co.uk/search?q=how+do+I+stop+a+thread+in+Java 28,000,000 個結果的可能重復項。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.