我正在学习用来ExectorService汇总threads和发送任务。我下面有一个简单的程序
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说
thread
executor.submit
executor.execute
submit
execute
API
方法提交通过创建并返回一个可以用来取消执行和/或等待完成的Future来扩展基本方法Executor.execute(java.lang.Runnable)。方法invokeAny和invokeAll执行批量执行的最常用形式,执行一组任务,然后等待至少一个或全部完成。(类ExecutorCompletionService可用于编写这些方法的自定义变体。)
但是我不清楚这到底是什么意思?
正如您从JavaDoc所看到的,execute(Runnable)它不返回任何内容。
execute(Runnable)
但是,submit(Callable<T>)返回一个Future对象,该对象允许您以后以编程方式取消正在运行的线程以及获取完成T时返回的线程Callable。有关更多详细信息,请参见Future的JavaDoc。
submit(Callable<T>)
Future
T
Callable
Future<?> future = executor.submit(longRunningJob); ... //long running job is taking too long future.cancel(true);
此外,如果future.get() == null并且不引发任何异常,则Runnable成功执行
future.get() == null