如何解决Java这段代码中的ExecutorService.submit和ExecutorService.execute有什么区别?
正如您从JavaDoc所看到的,execute(Runnable)
它不返回任何内容。
但是,submit(Callable<T>)
返回一个Future
对象,该对象允许您以后以编程方式取消正在运行的线程以及获取完成T
时返回的线程Callable
。有关更多详细信息,请参见Future的JavaDoc。
Future<?> future = executor.submit(longRunningJob);
...
//long running job is taking too long
future.cancel(true);
此外,如果future.get() == null
并且不引发任何异常,则Runnable成功执行
解决方法
我正在学习用来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
说
方法提交通过创建并返回一个可以用来取消执行和/或等待完成的Future来扩展基本方法Executor.execute(java.lang.Runnable)。方法invokeAny和invokeAll执行批量执行的最常用形式,执行一组任务,然后等待至少一个或全部完成。(类ExecutorCompletionService可用于编写这些方法的自定义变体。)
但是我不清楚这到底是什么意思?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。