11.线程池-4

execute和submit的区别

相同点:

1 都可以执行任务
2 参数都支持runnable

submit

execute

从图中可以看到两者的区别如下:

(1)来源

execute是Executor接口中的方法
submit是AbstractExecutorService中的方法

(2)接收参数类型

execute只能接受Runnable类型的任务
submit不管是Runnable还是Callable类型的任务都可以接受,但是Runnable返回值均为void,所以使用Future的get()获得的还是null

(3)返回值

execute没有返回值
submit有返回值,所以需要返回值的时候必须使用submit

(4)异常

execute中的是Runnable接口的实现,所以只能使用try、catch来捕获CheckedException,通过实现UncaughtExceptionHande接口处理UncheckedException
不管提交的是Runnable还是Callable类型的任务,如果不对返回值Future调用get()方法,都会吃掉异常。

package executors.threadpool;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
* <p></p>
*
* @author : wangdejian
* @version 1.0
* @date : 2021/8/4 21:01
*/
public class ThreadPoolExecute {
   public static void main(String[] args) {
       myTask();

   }

   public static void myTask() {

       ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2,
               5,
               5,
               TimeUnit.MINUTES,
               new ArrayBlockingQueue<>(6));

       for (int i = 0; i < 12; i++) {
           int tmp = i;
           threadPoolExecutor.execute(() -> {

               try {
                   System.out.println("--->" + Thread.currentThread().getName() + "--" + tmp);
                   Thread.sleep(1_000);
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }
           });
       }
       threadPoolExecutor.shutdown();
   }
}

public class ThreadPoolSubmit {
    public static void main(String[] args) throws ExecutionException, InterruptedException {

        Callable<Map<String, String>> callable = () -> {
            Map<String, String> map = new HashMap<>();
            try {
                Thread.sleep(1_000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            String toString = Thread.currentThread().toString();

            String name = Thread.currentThread().getName();
            System.out.println("toString=" + toString + ";name=" + name);
            map.put("toString", Thread.currentThread().toString());
            map.put("name", name);

            return map;
        };

        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5, 10,
                5, TimeUnit.MINUTES,
                new ArrayBlockingQueue<Runnable>(10));
        for (int i = 0; i < 10; i++) {
            Future<Map<String, String>> submit = threadPoolExecutor.submit(callable);
            System.out.println(submit.get().get("name"));
            System.out.println(submit.get().get("toString"));
        }

    }

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容