我正在编写一个生成多个并发任务的应用程序。我正在使用线程池来实现它。
可能会发生一个事件,使任务中正在进行的计算无效。在那种情况下,我想停止当前正在运行的任务,并开始新的任务。
我的问题:如何停止当前正在运行的任务?我实现的解决方案是存储对任务线程的引用,并在该线程上调用interrupt()
。在演示代码中:
public class Task implements Runnable {
private String name;
private Thread runThread;
public Task(String name) {
super();
this.name = name;
}
@Override
public void run() {
runThread = Thread.currentThread();
System.out.println("Starting thread " + name);
while (true) {
try {
Thread.sleep(4000);
System.out.println("Hello from thread " + name);
} catch (InterruptedException e) {
// We've been interrupted: no more messages.
return;
}
}
}
public void stop() {
runThread.interrupt();
}
public String getName() {
return name;
}
}
主要方法是:
public static void main(String args[]) {
executorService = Executors.newFixedThreadPool(2);
Task t1 = new Task("Task1");
Task t2 = new Task("Task2");
executorService.execute(t1);
executorService.execute(t2);
executorService.execute(new Task("Task3"));
executorService.execute(new Task("Task4"));
try {
Thread.sleep(12000);
t1.stop();
System.err.println("Stopped thread " + t1.getName());
Thread.sleep(8000);
t2.stop();
System.err.println("Stopped thread " + t2.getName());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
这是一个好的解决方案,还是有更好的方法来停止线程池中正在运行的线程?
最佳答案
你可以通过持有对 future 的引用来阻止它
Future<?> future = exec.submit( new Runnable() {
while (true){
try{
obj.wait();
} catch(InterruptedException e){
System.out.println("interrupted");
return;
}
}
});
future.cancel(true);
boolean 值用于 - 如果运行可能会中断。
我进行了测试,并从该线程获得了一个中断的异常。
如果你有 cachedThreadPool,你可能需要仔细检查你是否在你的 runnable 中捕获了异常,然后不要设置中断标志,因为你的线程将运行另一个 future ,如果你设置中断,另一个队列 future 可能无法运行。
关于java - 如何停止线程池中的线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3777772/