Java 線程池ExecutorService運行原理 和FutureTask 的使用


一.線程池ExecutorService運行原理

ThreadPoolExecutor中有corePoolSize(核心線程)和maximumPoolSize(工作線程),默認核心線程和工作線程數量一致。
1.當線ExecutorService線程池,使用submit,或者execute時
2.先判斷運行中的線程是否大於corePoolSize(核心線程)數量
3.如果大於corePoolSize(核心線程)且maximumPoolSize(工作線程)未滿則把該線程存着到工作線程等待。
4.如果大於corePoolSize(核心線程)且maximumPoolSize(工作線程)滿了則拋出異常(可配置處理策略)。
5.如果小於corePoolSize(核心線程)則把該線程立即運行。

二.代碼實現
package com.springboot.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.*;

@SpringBootApplication
public class DemoApplication {
    public static void main(String[] args)throws InterruptedException, ExecutionException {
        SpringApplication.run(DemoApplication.class, args);

        //定義線程池,ThreadPoolExecutor的方法實現,
        ExecutorService executorService = Executors.newFixedThreadPool(5);

        //用 FutureTask 包裝線程 可以得到返回值
        //isCancelled方法表示任務是否被取消成功,如果在任務正常完成前被取消成功,則返回 true。
        //isDone方法表示任務是否已經完成,若任務完成,則返回true;
        //get()方法用來獲取執行結果,這個方法會產生阻塞,會一直等到任務執行完畢才返回;
        //get(long timeout, TimeUnit unit)用來獲取執行結果,如果在指定時間內,還沒獲取到結果,就直接返回null。
        FutureTask<String> futureTaskCallable = new FutureTask<>(new TaskCallable());
        executorService.submit(futureTaskCallable);
        //打印執行結果
        System.out.println("執行結果:"+futureTaskCallable.get());

        //submit 方法 本質上也是調了execute 僅僅做了一個返回值包裝而已。
        //Runnable 類 submit execute 都可以執行
        executorService.submit(new TaskRunnable());
        executorService.execute(new TaskRunnable());
        //Callable類 只能 submit
        executorService.submit(new TaskCallable());

        //shutdown()與 shutdownNow() 的區別
        executorService.shutdown();//關閉線程池,不允許增加新的線程,但已有線程繼續運行至結束。
        executorService.shutdownNow();//關系線程池,線程池里的線程,立即停止執行。
    }
}
//實現Runnable 實現 run 方法
class TaskRunnable implements Runnable{
    @Override
    public void run(){
        System.out.println(Thread.currentThread().getName()
                +"##########實現 Runnable 重寫 run方法############");
    }
}
//實現Callable call方法
class TaskCallable implements Callable<String>{
    @Override
    public String call(){
        System.out.println(Thread.currentThread().getName()
                +"$$$$$$$$$$$實現Callable call方法$$$$$$$$$$$$$$");
        return Thread.currentThread().getName();
    }
}
 
        

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM