天天看點

java:線程池的submit和execute差別和源碼解析1背景2代碼實踐3 源碼解析

1背景

在回顧線程池的使用時,發現submit和execute,有很多相似之處,并對其進行了進一步的探索。

先上結論:

  1. 線程池中,不需要傳回值的pool.execute(runnable)
  2. 線程池中,需要傳回值的pool.submit(callable),或者,先進行包裝FutureTask futureTask = new FutureTask(callable);再executor.submit(futureTask);
  3. 普通線程中,不需要傳回值可以直接使用new Thread(runnable).start()
  4. 普通線程中,需要傳回值,先進行包裝FutureTask futureTask = new FutureTask(callable);再new Thread(futureTask).start(),結果通過futureTask的屬性方法進行檢視
  5. (有可能還有其他方法,水準有限,可能暫未列出)

2代碼實踐

最原始的submit和execute代碼實踐,submit執行callable接口類,execute執行runnable接口類

package com.zte.線程池實踐;

import java.util.concurrent.*;

public class CallableTask implements Callable, Runnable {
    private int flag;
    public static int ExceptionNumber = 666;

    public CallableTask(int flag) {
        this.flag = flag;
    }

    @Override
    public String call() throws Exception {
        System.out.println(Thread.currentThread().getName());
        if (flag == ExceptionNumber) {
            throw new Exception("flag is ExceptionNumber");
        }
        return flag % 2 == 0 ? "偶數" : "奇數";
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName());
        System.out.println(flag % 2 == 0 ? "偶數" : "奇數");
    }


    public static void main(String[] args) throws InterruptedException, ExecutionException {
        ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
        Runnable runnable1 = new CallableTask(1);
        Runnable runnable2 = new CallableTask(2);
        Runnable runnable3 = new CallableTask(666);
        cachedThreadPool.execute(runnable1);
        cachedThreadPool.execute(runnable2);
        cachedThreadPool.execute(runnable3);

        Thread.sleep(1000);

        Callable callable1 = new CallableTask(1);
        Callable callable2 = new CallableTask(2);
        Callable callable3 = new CallableTask(666);
        Future future1 = cachedThreadPool.submit(callable1);
        Future future2 = cachedThreadPool.submit(callable2);
        Future future3 = cachedThreadPool.submit(callable3);
        while (true) {
            if (future1.isDone() && future2.isDone() && future3.isDone()) {
                System.out.println("=====================inside=================while=====================");
                System.out.println(future1.get());//future 的 get 方法本身就是阻塞的,直接調用時會一直等到有了結果才會執行下一條語句
                System.out.println(future2.get());
                try {
                    //get 隻能get到call方法的傳回值,抛出的異常從調用get方法時一同抛出,異常還是應該使用try catch 捕捉
                    System.out.println(future3.get());
                } catch (Exception e) {
                    System.out.println(e);
                }

//                System.out.println(future3.get());
                break;
            }
            System.out.println("last line in while cycle");
        }
        cachedThreadPool.shutdown();
    }
}

           

3 源碼解析

可參考這篇大佬的文章:

https://blog.csdn.net/kai3123919064/article/details/90343380