一尘不染

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

java

我正在学习用来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。但我看不出输出有任何区别。以何种方式都submitexecute方法有什么不同?这个怎么API

方法提交通过创建并返回一个可以用来取消执行和/或等待完成的Future来扩展基本方法Executor.execute(java.lang.Runnable)。方法invokeAny和invokeAll执行批量执行的最常用形式,执行一组任务,然后等待至少一个或全部完成。(类ExecutorCompletionService可用于编写这些方法的自定义变体。)

但是我不清楚这到底是什么意思?


阅读 312

收藏
2020-12-03

共1个答案

一尘不染

正如您从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成功执行

2020-12-03