【发布时间】:2014-04-16 07:21:28
【问题描述】:
当我取消当前正在执行的任务时,我需要调用 MyThread.interrupt()。为什么不是public class Main {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(10);
List<MyThread> threads = new ArrayList<Main.MyThread>();
List<Future> futureList = new ArrayList<Future>();
for (int i = 0; i < 30; i++) {
MyThread myThread = new MyThread(i);
futureList.add(executor.submit(myThread));
threads.add(myThread);
}
for (Future future : futureList) {
if (future != null) {
future.cancel(true);
}
}
// Calling interrupt directly. It works
for (MyThread myThread : threads) {
myThread.interrupt();
}
shutdownAndAwaitTermination(executor);
}
static void shutdownAndAwaitTermination(ExecutorService pool) {
pool.shutdown(); // Disable new tasks from being submitted
try {
// Wait a while for existing tasks to terminate
if (!pool.awaitTermination(10, TimeUnit.SECONDS)) {
pool.shutdownNow(); // Cancel currently executing tasks
// Wait a while for tasks to respond to being cancelled
if (!pool.awaitTermination(10, TimeUnit.SECONDS)) System.err.println("Pool did not terminate");
else System.out.println("Maybe OK");
} else {
System.out.println("OK");
}
} catch (InterruptedException ie) {
// (Re-)Cancel if current thread also interrupted
pool.shutdownNow();
// Preserve interrupt status
Thread.currentThread().interrupt();
}
}
private static class MyThread extends Thread {
HttpURLConnection connection;
final int i;
public MyThread(int i) {
this.i = i;
}
@Override
public void interrupt() {
super.interrupt();
if (connection != null) {
connection.disconnect();
}
}
@Override
public void run() {
// Initialize HttpURLConnection and upload / download data
}
}
}
【问题讨论】:
标签: java multithreading threadpool interrupt