我在写一个产生多个并发任务的应用程序。我正在使用线程池来实现它。如何停止线程池中的线程
可能发生的事件发生使得任务中的计算无效。在这种情况下,我想停止当前正在运行的任务,并开始新的任务。
我的问题:如何停止当前正在运行的任务?我实现的解决方案是存储对任务线程的引用,并在此线程上调用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();
}
}
这是一个很好的解决方案,或者有更好的办法阻止在一个线程池正在运行的线程?
拔插头;) – sje397 2010-09-23 11:27:20