我一直在检查类似的问题。This one和我想问的很相似,但我并不是真的有答案。还有This question我已经检查过了。
我的问题是,我有一个SwingWorker,它在后台执行长时间的处理。
@Override
protected final List<Object> doInBackground() throws Exception
{
//Should I add if(this.isCancelled) here?
List<Object> objectList = someFecthingMethod();
//Should I add if(this.isCancelled) here?
objectList.forEach(object -> executor.submit(new Helper(object));
this.latch.await();
//Should I add if(this.isCancelled) here?
someOtherLongRunningMethodBasedOnHelperResults();
}在scratch中,我有一个这样的代码。这运行时,我的计算按钮,触发工人时,它被点击。我也希望能够取消它。我已经编写了needed stop(),其中包含worker本身的cancel()方法。
在我的Worker类中,我有如下的stop方法:
@Override
public boolean stop()
{
return this.cancel( true );
} 当我调用这个方法时,我签入doInBackground(),this.isCancelled()返回true.。但不管怎样,它一直在执行doInBackground()中的方法。所以我的问题是,我是否应该在doInBackground()中的每个方法之前添加if(this.isCancelled())检查来立即停止它,有没有更好的方法来阻止它在被取消时执行?
提前谢谢你。
发布于 2018-11-26 18:15:18
您可以创建一个包装器,以提供取消闩锁的功能。它将需要跟踪等待线程,并在它们超时时释放它们,同时记住锁存已被取消,因此将来对await的调用将立即中断。
https://stackoverflow.com/questions/53478783
复制相似问题