【发布时间】:2017-06-06 12:41:10
【问题描述】:
我需要中断 swingworkers,但如果线程正在运行某个片段,它应该在那之后中断。像这样的:
public class worker extends SwingWorker<Integer, String>{
//(...) constructors and everything else
protected Integer doInBackground() throws Exception{
//Code that can be interrupted
while(true){
//(...) more code that can be interrupted
//This shouldn't be interrupted, has to wait till the loop ends
for(int i=0; i<10; i++){
//(...) more code that can be interrupted
}
}
}
用以下方式打断工人:
Worker worker = new Worker();
worker.execute();
worker.cancel(true);
我已经尝试过同步块,但不确定这是行不通还是我做错了。
有办法吗?谢谢!
【问题讨论】:
-
如this answer 中所述,您不会中断线程。您以受控方式结束线程。
标签: java multithreading swingworker