gpt4 book ai didi

java - Java 中这段代码中的 ExecutorService.submit 和 ExecutorService.execute 有什么区别?

转载 作者:IT老高 更新时间:2023-10-28 20:35:52 27 4
gpt4 key购买 nike

我正在学习使用 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个任务。在每个 thread 完成其任务后,它会执行下一个任务,在上面的代码中,我使用了 executor.submit。我也改成了executor.execute。但我看不出输出有什么不同。 submitexecute 方法有何不同?这就是 API 所说的

Method submit extends base method Executor.execute(java.lang.Runnable) by creating and returning a Future that can be used to cancel execution and/or wait for completion. Methods invokeAny and invokeAll perform the most commonly useful forms of bulk execution, executing a collection of tasks and then waiting for at least one, or all, to complete. (Class ExecutorCompletionService can be used to write customized variants of these methods.)

但我不清楚它的确切含义是什么?

最佳答案

正如您从 JavaDoc execute(Runnable) 中看到的那样不返回任何东西。

但是,submit(Callable<T>)返回 Future对象,它允许您稍后以编程方式取消正在运行的线程并获取 TCallable 时返回完成。见 JavaDoc of Future了解更多

Future<?> future = executor.submit(longRunningJob);
...
//long running job is taking too long
future.cancel(true);

此外,如果 future.get() == null并且不抛出任何异常然后 Runnable 成功执行

关于java - Java 中这段代码中的 ExecutorService.submit 和 ExecutorService.execute 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18730290/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com