如何提交一个任务到线程池执行?

如何创建线程池之ThreadPoolExecutor构造方法参数解析
如何创建线程池之Executors类的使用

提交任务到线程池执行有以下几种办法:

使用execute方法,无返回值

ExecutorService executor = Executors.newCachedThreadPool();
Runnable runnable = new Runnable() {
    @Override
    public void run() {
        System.out.println("do something");
    }
};
executor.execute(runnable);

入参为常见的Runnable类型

使用submit方法,有返回值

submit有3个重载函数,最常用的是下面这个

<T> Future<T> submit(Callable<T> task);

入参为Callable类型,可以通过返回的Future对象获取call方法的执行结果。

ExecutorService executor = Executors.newCachedThreadPool();
Callable<String> callable = new Callable<String>() {
    @Override
    public String call() throws Exception {
        System.out.println("do something");
        return "finished";
    }
};
Future<String> submit = executor.submit(callable);
//阻塞主线程,等待任务执行完毕,返回值为call()的返回值
System.out.println(submit.get());

其余2个我个人感觉没啥用,了解一下即可。

Future<?> submit(Runnable task);

虽然返回了一个Future对象,但是这个对象没有返回值,作用只是可以通过get方法阻塞主线程等待任务执行完毕(好像没啥用)

ExecutorService executor = Executors.newCachedThreadPool();
Runnable runnable = new Runnable() {
    @Override
    public void run() {
        System.out.println("do something");
    }
};
Future<?> submit = executor.submit(runnable);
//阻塞主线程,等待任务执行完毕,返回值为null
System.out.println(submit.get());
<T> Future<T> submit(Runnable task, T result);

与上一个方法的区别是,返回值固定为result,可以自定义返回值(一样好像没啥用)

ExecutorService executor = Executors.newCachedThreadPool();
Runnable runnable = new Runnable() {
    @Override
    public void run() {
        System.out.println("do something");
    }
};
Future<String> submit = executor.submit(runnable, "finished");
//阻塞主线程,等待任务执行完毕,返回值为finished
System.out.println(submit.get());

觉得内容还不错?打赏个钢镚鼓励鼓励!!👍