我在寫一個產生多個併發任務的應用程序。我正在使用線程池來實現它。如何停止線程池中的線程
可能發生的事件發生使得任務中的計算無效。在這種情況下,我想停止當前正在運行的任務,並開始新的任務。
我的問題:如何停止當前正在運行的任務?我實現的解決方案是存儲對任務線程的引用,並在此線程上調用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