我正在学习使用ExectorService
来池化threads
并发送任务。我有一个简单的程序如下:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
class Processor implements Runnable {
private int id;
public Processor(int id) {
this.id = id;
}
public void run() {
System.out.println("Starting: " + id);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
System.out.println("sorry, being interupted, good bye!");
System.out.println("Interrupted " + Thread.currentThread().getName());
e.printStackTrace();
}
System.out.println("Completed: " + id);
}
}
public class ExecutorExample {
public static void main(String[] args) {
Boolean isCompleted = false;
ExecutorService executor = Executors.newFixedThreadPool(2);
for (int i = 0; i < 5; i++) {
executor.execute(new Processor(i));
}
//executor does not accept any more tasks but the submitted tasks continue
executor.shutdown();
System.out.println("All tasks submitted.");
try {
//wait for the exectutor to terminate normally, which will return true
//if timeout happens, returns false, but this does NOT interrupt the threads
isCompleted = executor.awaitTermination(100, TimeUnit.SECONDS);
//this will interrupt thread it manages. catch the interrupted exception in the threads
//If not, threads will run forever and executor will never be able to shutdown.
executor.shutdownNow();
} catch (InterruptedException e) {
}
if (isCompleted) {
System.out.println("All tasks completed.");
} else {
System.out.println("Timeout " + Thread.currentThread().getName());
}
}
}
它没有任何花哨的功能,但创建了两个线程并总共提交了5个任务。每个线程完成其任务后,它会接下来执行下一个任务。
在上面的代码中,我使用了executor.submit
。我还改为了executor.execute
。但我没有看到输出中有任何区别。submit
和execute
方法有什么不同?
这是API
所说的内容:"方法submit通过创建和返回可以用于取消执行和/或等待完成的Future,扩展了基本方法Executor.execute(java.lang.Runnable)。方法invokeAny和invokeAll执行最常用的批量执行形式,即执行一组任务,然后等待至少一个或全部完成。(类ExecutorCompletionService可用于编写这些方法的自定义变体。)"
但是我不清楚它确切的含义是什么?
execute(...)
运行的作业抛出异常,则线程将在此过程中被终止,然后可能由ExecutorService
重新启动。 - Gray