我正在学习使用 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());
}
}
}
它没有什么特别之处,但是创建了两个 threads
并且总共提交了5个任务。在每个 thread
完成它的任务之后,它接受下一个任务,
在上面的代码中,我使用 executor.submit
。我也换成了 executor.execute
。但是我没有看到任何输出上的差异。submit
和 execute
的方法在哪些方面不同?
API
是这么说的
方法提交扩展了基本方法 Executor.execute (java.lang。通过创建并返回一个 Future,该 Future 可用于取消执行和/或等待完成。方法 invkeAnyandinvkeAll 执行最常用的批量执行形式,执行一组任务,然后等待至少一个或全部任务完成。(类 ExecutorCompletionService 可用于编写这些方法的自定义变体。)
但我不清楚它到底是什么意思?