Java中此代码中的executor.submit和executor.execute之间的区别? [英] difference between executor.submit and executor.execute in this code in Java?

查看:416
本文介绍了Java中此代码中的executor.submit和executor.execute之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习使用 exectorServices 来汇总线程并发送任务。我有一个简单的程序

I am learning to use exectorServices to pool threads and send out tasks. I have a simple program below

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个任务。在每个线程完成其任务后,它需要下一个,
在上面的代码中,我使用 executor.submit 。我还改为 executor.execute 。但我没有看到输出有任何差异。以什么方式提交和执行方法有何不同?
这就是 API 所说的

It does nothing fancy, but creates two threads and submits 5 tasks in total. After each thread completes its task, it takes the next one, In the code above, I use executor.submit. I also changed to executor.execute. But I do not see any difference in the output. In what way are the submit and execute methods different? This what the API says


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

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.)

但我不清楚它究竟意味着什么?
谢谢

But its not clear to me as what it exactly means? Thanks

推荐答案

从JavaDoc 执行(Runnable)不返回任何内容。

As you see from the JavaDoc execute(Runnable) does not return anything.

然而,提交(Callable< T>)返回 Future 对象,它允许您以某种方式以编程方式取消正在运行的线程,以及获取 T 时返回的可调用完成。有关更多详细信息,请参见 JavaDoc of Future

However, submit(Callable<T>) returns a Future object which allows a way for you to programatically cancel the running thread later as well as get the T that is returned when the Callable completes. See JavaDoc of Future for more details

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

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

Moreover, if future.get() == null and doesn't throw any exception then Runnable executed successfully

这篇关于Java中此代码中的executor.submit和executor.execute之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆