最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

非常適合新手學(xué)生的Java線程池優(yōu)化升級(jí)版

 更新時(shí)間:2022年03月30日 17:16:47   作者:摸魚打醬油  
作者是一個(gè)來(lái)自河源的大三在校生,以下筆記都是作者自學(xué)之路的一些淺薄經(jīng)驗(yàn),如有錯(cuò)誤請(qǐng)指正,將來(lái)會(huì)不斷的完善筆記,幫助更多的Java愛好者入門

升級(jí)版線程池的優(yōu)化

1:新增了4種拒絕策略。分別為:MyAbortPolicy、MyDiscardPolicy、MyDiscardOldestPolicy、MyCallerRunsPolicy

2:對(duì)線程池MyThreadPoolExecutor的構(gòu)造方法進(jìn)行優(yōu)化,增加了參數(shù)校驗(yàn),防止亂傳參數(shù)現(xiàn)象。

3:這是最重要的一個(gè)優(yōu)化。

  • 移除線程池的線程預(yù)熱功能。因?yàn)榫€程預(yù)熱會(huì)極大的耗費(fèi)內(nèi)存,當(dāng)我們不用線程池時(shí)也會(huì)一直在運(yùn)行狀態(tài)。
  • 換來(lái)的是在調(diào)用execute方法添加任務(wù)時(shí)通過(guò)檢查workers線程集合目前的大小與corePoolSize的值去比較,再通過(guò)new MyWorker()去創(chuàng)建添加線程到線程池,這樣好處就是當(dāng)我們創(chuàng)建線程池如果不使用的話則對(duì)當(dāng)前內(nèi)存沒(méi)有一點(diǎn)影響,當(dāng)使用了才會(huì)創(chuàng)建線程并放入線程池中進(jìn)行復(fù)用。

線程池構(gòu)造器

    public MyThreadPoolExecutor(){
        this(5,new ArrayBlockingQueue<>(10), Executors.defaultThreadFactory(),defaultHandle);
    }
    public MyThreadPoolExecutor(int corePoolSize, BlockingQueue<Runnable> waitingQueue,ThreadFactory threadFactory) {
        this(corePoolSize,waitingQueue,threadFactory,defaultHandle);
    }
    public MyThreadPoolExecutor(int corePoolSize, BlockingQueue<Runnable> waitingQueue,ThreadFactory threadFactory,MyRejectedExecutionHandle handle) {
        this.workers=new HashSet<>(corePoolSize);
        if(corePoolSize>=0&&waitingQueue!=null&&threadFactory!=null&&handle!=null){
            this.corePoolSize=corePoolSize;
            this.waitingQueue=waitingQueue;
            this.threadFactory=threadFactory;
            this.handle=handle;
        }else {
            throw new NullPointerException("線程池參數(shù)不合法");
        }
    }

線程池拒絕策略

策略接口:MyRejectedExecutionHandle

package com.springframework.concurrent;

/**
 * 自定義拒絕策略
 * @author 游政杰
 */
public interface MyRejectedExecutionHandle {

    void rejectedExecution(Runnable runnable,MyThreadPoolExecutor threadPoolExecutor);

}

策略內(nèi)部實(shí)現(xiàn)類

/**
     * 實(shí)現(xiàn)自定義拒絕策略
     */
    //拋異常策略(默認(rèn))
    public static class MyAbortPolicy implements MyRejectedExecutionHandle{
        public MyAbortPolicy(){

        }
        @Override
        public void rejectedExecution(Runnable r, MyThreadPoolExecutor t) {
            throw new MyRejectedExecutionException("任務(wù)-> "+r.toString()+"被線程池-> "+t.toString()+" 拒絕");
        }
    }
    //默默丟棄策略
    public static class MyDiscardPolicy implements MyRejectedExecutionHandle{

        public MyDiscardPolicy() {
        }
        @Override
        public void rejectedExecution(Runnable runnable, MyThreadPoolExecutor threadPoolExecutor) {

        }
    }
    //丟棄掉最老的任務(wù)策略
    public static class MyDiscardOldestPolicy implements MyRejectedExecutionHandle{
        public MyDiscardOldestPolicy() {
        }
        @Override
        public void rejectedExecution(Runnable runnable, MyThreadPoolExecutor threadPoolExecutor) {
            if(!threadPoolExecutor.isShutdown()){ //如果線程池沒(méi)被關(guān)閉
                threadPoolExecutor.getWaitingQueue().poll();//丟掉最老的任務(wù),此時(shí)就有位置當(dāng)新任務(wù)了
                threadPoolExecutor.execute(runnable); //把新任務(wù)加入到隊(duì)列中
            }
        }
    }
    //由調(diào)用者調(diào)用策略
    public static class MyCallerRunsPolicy implements MyRejectedExecutionHandle{
        public MyCallerRunsPolicy(){

        }
        @Override
        public void rejectedExecution(Runnable runnable, MyThreadPoolExecutor threadPoolExecutor) {
            if(!threadPoolExecutor.isShutdown()){//判斷線程池是否被關(guān)閉
                runnable.run();
            }
        }
    }

封裝拒絕方法

    protected final void reject(Runnable runnable){
        this.handle.rejectedExecution(runnable, this);
    }

    protected final void reject(Runnable runnable,MyThreadPoolExecutor threadPoolExecutor){
        this.handle.rejectedExecution(runnable, threadPoolExecutor);
    }

execute方法

    @Override
    public boolean execute(Runnable runnable)
    {
        if (!this.waitingQueue.offer(runnable)) {
            this.reject(runnable);
            return false;
        }
        else {
            if(this.workers!=null&&this.workers.size()<corePoolSize){//這種情況才能添加線程
                MyWorker worker = new MyWorker(); //通過(guò)構(gòu)造方法添加線程
            }
            return true;
        }
    }

可以看出只有當(dāng)往線程池放任務(wù)時(shí)才會(huì)創(chuàng)建線程對(duì)象。

手寫線程池源碼

MyExecutorService

package com.springframework.concurrent;

import java.util.concurrent.BlockingQueue;

/**
 * 自定義線程池業(yè)務(wù)接口
 * @author 游政杰
 */
public interface MyExecutorService {

    boolean execute(Runnable runnable);

    void shutdown();

    void shutdownNow();

    boolean isShutdown();

    BlockingQueue<Runnable> getWaitingQueue();

}

MyRejectedExecutionException

package com.springframework.concurrent;

/**
 * 自定義拒絕異常
 */
public class MyRejectedExecutionException extends RuntimeException {

    public MyRejectedExecutionException() {
    }
    public MyRejectedExecutionException(String message) {
        super(message);
    }

    public MyRejectedExecutionException(String message, Throwable cause) {
        super(message, cause);
    }

    public MyRejectedExecutionException(Throwable cause) {
        super(cause);
    }

}

MyRejectedExecutionHandle

package com.springframework.concurrent;

/**
 * 自定義拒絕策略
 * @author 游政杰
 */
public interface MyRejectedExecutionHandle {

    void rejectedExecution(Runnable runnable,MyThreadPoolExecutor threadPoolExecutor);

}

核心類MyThreadPoolExecutor

package com.springframework.concurrent;

import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 純手?jǐn)]線程池框架
 * @author 游政杰
 */
public class MyThreadPoolExecutor implements MyExecutorService{

    private static final AtomicInteger taskcount=new AtomicInteger(0);//執(zhí)行任務(wù)次數(shù)
    private static final AtomicInteger threadNumber=new AtomicInteger(0); //線程編號(hào)
    private static volatile int corePoolSize; //核心線程數(shù)
    private final HashSet<MyWorker> workers; //工作線程
    private final BlockingQueue<Runnable> waitingQueue; //等待隊(duì)列
    private static final String THREADPOOL_NAME="MyThread-Pool-";//線程名稱
    private volatile boolean isRunning=true; //是否運(yùn)行
    private volatile boolean STOPNOW=false; //是否立刻停止
    private volatile ThreadFactory threadFactory; //線程工廠
    private static final MyRejectedExecutionHandle defaultHandle=new MyThreadPoolExecutor.MyAbortPolicy();//默認(rèn)拒絕策略
    private volatile MyRejectedExecutionHandle handle; //拒絕紫略

    public MyThreadPoolExecutor(){
        this(5,new ArrayBlockingQueue<>(10), Executors.defaultThreadFactory(),defaultHandle);
    }
    public MyThreadPoolExecutor(int corePoolSize, BlockingQueue<Runnable> waitingQueue,ThreadFactory threadFactory) {
        this(corePoolSize,waitingQueue,threadFactory,defaultHandle);
    }
    public MyThreadPoolExecutor(int corePoolSize, BlockingQueue<Runnable> waitingQueue,ThreadFactory threadFactory,MyRejectedExecutionHandle handle) {
        this.workers=new HashSet<>(corePoolSize);
        if(corePoolSize>=0&&waitingQueue!=null&&threadFactory!=null&&handle!=null){
            this.corePoolSize=corePoolSize;
            this.waitingQueue=waitingQueue;
            this.threadFactory=threadFactory;
            this.handle=handle;
        }else {
            throw new NullPointerException("線程池參數(shù)不合法");
        }
    }
    /**
     * 實(shí)現(xiàn)自定義拒絕策略
     */
    //拋異常策略(默認(rèn))
    public static class MyAbortPolicy implements MyRejectedExecutionHandle{
        public MyAbortPolicy(){

        }
        @Override
        public void rejectedExecution(Runnable r, MyThreadPoolExecutor t) {
            throw new MyRejectedExecutionException("任務(wù)-> "+r.toString()+"被線程池-> "+t.toString()+" 拒絕");
        }
    }
    //默默丟棄策略
    public static class MyDiscardPolicy implements MyRejectedExecutionHandle{

        public MyDiscardPolicy() {
        }
        @Override
        public void rejectedExecution(Runnable runnable, MyThreadPoolExecutor threadPoolExecutor) {

        }
    }
    //丟棄掉最老的任務(wù)策略
    public static class MyDiscardOldestPolicy implements MyRejectedExecutionHandle{
        public MyDiscardOldestPolicy() {
        }
        @Override
        public void rejectedExecution(Runnable runnable, MyThreadPoolExecutor threadPoolExecutor) {
            if(!threadPoolExecutor.isShutdown()){ //如果線程池沒(méi)被關(guān)閉
                threadPoolExecutor.getWaitingQueue().poll();//丟掉最老的任務(wù),此時(shí)就有位置當(dāng)新任務(wù)了
                threadPoolExecutor.execute(runnable); //把新任務(wù)加入到隊(duì)列中
            }
        }
    }
    //由調(diào)用者調(diào)用策略
    public static class MyCallerRunsPolicy implements MyRejectedExecutionHandle{
        public MyCallerRunsPolicy(){

        }
        @Override
        public void rejectedExecution(Runnable runnable, MyThreadPoolExecutor threadPoolExecutor) {
            if(!threadPoolExecutor.isShutdown()){//判斷線程池是否被關(guān)閉
                runnable.run();
            }
        }
    }
    //call拒絕方法
    protected final void reject(Runnable runnable){
        this.handle.rejectedExecution(runnable, this);
    }

    protected final void reject(Runnable runnable,MyThreadPoolExecutor threadPoolExecutor){
        this.handle.rejectedExecution(runnable, threadPoolExecutor);
    }

    /**
     * MyWorker就是我們每一個(gè)線程對(duì)象
     */
    private final class MyWorker implements Runnable{

        final Thread thread; //為每個(gè)MyWorker

        MyWorker(){
            Thread td = threadFactory.newThread(this);
            td.setName(THREADPOOL_NAME+threadNumber.getAndIncrement());
            this.thread=td;
            this.thread.start();
            workers.add(this);
        }

        //執(zhí)行任務(wù)
        @Override
        public void run() {
            //循環(huán)接收任務(wù)
                while (true)
                {
                    //循環(huán)退出條件:
                    //1:當(dāng)isRunning為false并且waitingQueue的隊(duì)列大小為0(也就是無(wú)任務(wù)了),會(huì)優(yōu)雅的退出。
                    //2:當(dāng)STOPNOW為true,則說(shuō)明調(diào)用了shutdownNow方法進(jìn)行暴力退出。
                    if((!isRunning&&waitingQueue.size()==0)||STOPNOW)
                    {
                        break;
                    }else {
                        //不斷取任務(wù),當(dāng)任務(wù)!=null時(shí)則調(diào)用run方法處理任務(wù)
                        Runnable runnable = waitingQueue.poll();
                        if(runnable!=null){
                            runnable.run();
                            System.out.println("task==>"+taskcount.incrementAndGet());
                        }
                    }
                }
        }
    }

    //往線程池中放任務(wù)
    @Override
    public boolean execute(Runnable runnable)
    {
        if (!this.waitingQueue.offer(runnable)) {
            this.reject(runnable);
            return false;
        }
        else {
            if(this.workers!=null&&this.workers.size()<corePoolSize){//這種情況才能添加線程
                MyWorker worker = new MyWorker(); //通過(guò)構(gòu)造方法添加線程
            }
            return true;
        }
    }
    //優(yōu)雅的關(guān)閉
    @Override
    public void shutdown()
    {
        this.isRunning=false;
    }
    //暴力關(guān)閉
    @Override
    public void shutdownNow()
    {
        this.STOPNOW=true;
    }

    //判斷線程池是否關(guān)閉
    @Override
    public boolean isShutdown() {
        return !this.isRunning||STOPNOW;
    }

    //獲取等待隊(duì)列
    @Override
    public BlockingQueue<Runnable> getWaitingQueue() {
        return this.waitingQueue;
    }
}

線程池測(cè)試類

package com.springframework.test;

import com.springframework.concurrent.MyThreadPoolExecutor;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;

public class ThreadPoolTest {

  public static void main(String[] args) {


//      MyThreadPoolExecutor myThreadPoolExecutor = new MyThreadPoolExecutor
//              (5,new ArrayBlockingQueue<>(6), Executors.defaultThreadFactory(),new MyThreadPoolExecutor.MyAbortPolicy());

//      MyThreadPoolExecutor myThreadPoolExecutor = new MyThreadPoolExecutor
//              (5,new ArrayBlockingQueue<>(6), Executors.defaultThreadFactory(),new MyThreadPoolExecutor.MyDiscardPolicy());

//      MyThreadPoolExecutor myThreadPoolExecutor = new MyThreadPoolExecutor
//              (5,new ArrayBlockingQueue<>(6), Executors.defaultThreadFactory(),new MyThreadPoolExecutor.MyDiscardOldestPolicy());

      MyThreadPoolExecutor myThreadPoolExecutor = new MyThreadPoolExecutor
              (5,new ArrayBlockingQueue<>(6), Executors.defaultThreadFactory(),new MyThreadPoolExecutor.MyCallerRunsPolicy());


      for(int i=0;i<11;i++){

          int finalI = i;
          myThreadPoolExecutor.execute(()->{
              System.out.println(Thread.currentThread().getName()+">>>>"+ finalI);
          });

      }

      myThreadPoolExecutor.shutdown();

//      myThreadPoolExecutor.shutdownNow();




  }
}

好了升級(jí)版線程池就優(yōu)化到這了,后面可能還會(huì)出完善版,不斷進(jìn)行優(yōu)化。

到此這篇關(guān)于非常適合新手學(xué)生的Java線程池升級(jí)版的文章就介紹到這了,更多相關(guān)Java 線程池內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Java中Socket設(shè)置連接超時(shí)的代碼分享

    Java中Socket設(shè)置連接超時(shí)的代碼分享

    在我們?nèi)粘_B接中,如果超時(shí)時(shí)長(zhǎng)過(guò)長(zhǎng)的話,在開發(fā)時(shí)會(huì)影響測(cè)試,下面這篇文章主要給大家分享了關(guān)于Java中Socket設(shè)置連接超時(shí)的代碼,需要的朋友可以參考借鑒,下面來(lái)一起看看吧。
    2017-06-06
  • Java編程實(shí)現(xiàn)快速排序及優(yōu)化代碼詳解

    Java編程實(shí)現(xiàn)快速排序及優(yōu)化代碼詳解

    這篇文章主要介紹了Java編程實(shí)現(xiàn)快速排序及優(yōu)化代碼詳解,具有一定借鑒價(jià)值,需要的朋友可以了解下。
    2017-12-12
  • 使用JWT創(chuàng)建解析令牌及RSA非對(duì)稱加密詳解

    使用JWT創(chuàng)建解析令牌及RSA非對(duì)稱加密詳解

    這篇文章主要介紹了JWT創(chuàng)建解析令牌及RSA非對(duì)稱加密詳解,JWT是JSON Web Token的縮寫,即JSON Web令牌,是一種自包含令牌,一種情況是webapi,類似之前的阿里云播放憑證的功能,另一種情況是多web服務(wù)器下實(shí)現(xiàn)無(wú)狀態(tài)分布式身份驗(yàn)證,需要的朋友可以參考下
    2023-11-11
  • java解析.yml文件方式

    java解析.yml文件方式

    這篇文章主要介紹了java解析.yml文件方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-01-01
  • Java中Cookie和Session詳解及區(qū)別總結(jié)

    Java中Cookie和Session詳解及區(qū)別總結(jié)

    這篇文章主要介紹了Java中Cookie和Session詳解,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,感興趣的小伙伴可以參考一下
    2022-06-06
  • Java?IPage分頁(yè)操作 附加自定義sql

    Java?IPage分頁(yè)操作 附加自定義sql

    這篇文章主要介紹了Java?IPage分頁(yè)加自定義sql,主要包括引入依賴,impl常規(guī)操作,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2022-06-06
  • 快速搭建Spring Boot+MyBatis的項(xiàng)目IDEA(附源碼下載)

    快速搭建Spring Boot+MyBatis的項(xiàng)目IDEA(附源碼下載)

    這篇文章主要介紹了快速搭建Spring Boot+MyBatis的項(xiàng)目IDEA(附源碼下載),本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2020-12-12
  • Mybatis?Plus批處理操作的實(shí)現(xiàn)示例

    Mybatis?Plus批處理操作的實(shí)現(xiàn)示例

    MyBatis?Plus?提供了強(qiáng)大的批處理支持,可以幫助我們高效地處理大規(guī)模數(shù)據(jù),本文主要介紹了Mybatis?Plus批處理操作的實(shí)現(xiàn)示例,具有一定的參考價(jià)值,感興趣的可以了解一下
    2024-07-07
  • Java類加載器與雙親委派機(jī)制和線程上下文類加載器專項(xiàng)解讀分析

    Java類加載器與雙親委派機(jī)制和線程上下文類加載器專項(xiàng)解讀分析

    類加載器負(fù)責(zé)讀取Java字節(jié)代碼,并轉(zhuǎn)換成java.lang.Class類的一個(gè)實(shí)例的代碼模塊。本文主要和大家聊聊JVM類加載器ClassLoader的使用,需要的可以了解一下
    2022-12-12
  • Java數(shù)據(jù)結(jié)構(gòu)通關(guān)時(shí)間復(fù)雜度和空間復(fù)雜度

    Java數(shù)據(jù)結(jié)構(gòu)通關(guān)時(shí)間復(fù)雜度和空間復(fù)雜度

    對(duì)于一個(gè)算法,其時(shí)間復(fù)雜度和空間復(fù)雜度往往是相互影響的,當(dāng)追求一個(gè)較好的時(shí)間復(fù)雜度時(shí),可能會(huì)使空間復(fù)雜度的性能變差,即可能導(dǎo)致占用較多的存儲(chǔ)空間,這篇文章主要給大家介紹了關(guān)于Java時(shí)間復(fù)雜度、空間復(fù)雜度的相關(guān)資料,需要的朋友可以參考下
    2022-05-05

最新評(píng)論

剑河县| 新巴尔虎右旗| 淮南市| 泰和县| 辽宁省| 荣昌县| 陈巴尔虎旗| 醴陵市| 龙南县| 永善县| 得荣县| 浪卡子县| 通化县| 宣化县| 绥江县| 驻马店市| 淮阳县| 沭阳县| 军事| 凤冈县| 从江县| 剑阁县| 双辽市| 四川省| 延寿县| 武威市| 沈阳市| 铜川市| 新昌县| 沙坪坝区| 秦皇岛市| 舞阳县| 定边县| 长寿区| 恩施市| 德钦县| 汪清县| 东源县| 外汇| 铁岭市| 大兴区|