欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

 更新時(shí)間:2022年03月30日 17:16:47   作者:摸魚打醬油  
作者是一個(gè)來自河源的大三在校生,以下筆記都是作者自學(xué)之路的一些淺薄經(jīng)驗(yàn),如有錯(cuò)誤請(qǐng)指正,將來會(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)。
  • 換來的是在調(diào)用execute方法添加任務(wù)時(shí)通過檢查workers線程集合目前的大小與corePoolSize的值去比較,再通過new MyWorker()去創(chuàng)建添加線程到線程池,這樣好處就是當(dāng)我們創(chuàng)建線程池如果不使用的話則對(duì)當(dāng)前內(nè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()){ //如果線程池沒被關(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(); //通過構(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()){ //如果線程池沒被關(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ù)了),會(huì)優(yōu)雅的退出。
                    //2:當(dāng)STOPNOW為true,則說明調(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(); //通過構(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)文章

  • 詳解MyBatis特性之動(dòng)態(tài)SQL

    詳解MyBatis特性之動(dòng)態(tài)SQL

    動(dòng)態(tài) SQL 是 MyBatis 的強(qiáng)大特性之一,這篇文章我們將結(jié)合動(dòng)態(tài)SQL完成更加復(fù)雜的 SQL 操作,文章通過代碼示例給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作有一定的幫助,需要的朋友可以參考下
    2024-01-01
  • Java的synchronized關(guān)鍵字深入解析

    Java的synchronized關(guān)鍵字深入解析

    這篇文章主要介紹了Java的synchronized關(guān)鍵字深入解析,在并發(fā)編程中,多線程同時(shí)并發(fā)訪問的資源叫做臨界資源,當(dāng)多個(gè)線程同時(shí)訪問對(duì)象并要求操作相同資源時(shí),分割了原子操作就有可能出現(xiàn)數(shù)據(jù)的不一致或數(shù)據(jù)不完整的情況,需要的朋友可以參考下
    2023-12-12
  • Java?Bean?Validation使用示例詳解

    Java?Bean?Validation使用示例詳解

    這篇文章主要為大家介紹了Java?Bean?Validation的使用示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-11-11
  • Java 單例模式的實(shí)現(xiàn)資料整理

    Java 單例模式的實(shí)現(xiàn)資料整理

    這篇文章主要介紹了Java 單例模式的實(shí)現(xiàn)的相關(guān)資料,并附簡(jiǎn)單實(shí)例代碼,需要的朋友可以參考下
    2016-10-10
  • Java中設(shè)置session超時(shí)(失效)的三種方法

    Java中設(shè)置session超時(shí)(失效)的三種方法

    這篇文章主要介紹了Java中設(shè)置session超時(shí)(失效)的三種方法,本文講解了在web容器中設(shè)置、在工程的web.xml中設(shè)置、通過java代碼設(shè)置3種方法,需要的朋友可以參考下
    2015-07-07
  • JAVA自定義注解詳情

    JAVA自定義注解詳情

    這篇文章主要介紹了Java自定義注解,結(jié)合實(shí)例形式總結(jié)分析了java常見的自定義注解類型、功能、用法及操作注意事項(xiàng),需要的朋友可以參考下
    2021-10-10
  • Java中Map實(shí)現(xiàn)線程安全的3種方式

    Java中Map實(shí)現(xiàn)線程安全的3種方式

    本文主要介紹了Java中Map實(shí)現(xiàn)線程安全的3種方式,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2022-03-03
  • Spring事務(wù)處理Transactional,鎖同步和并發(fā)線程

    Spring事務(wù)處理Transactional,鎖同步和并發(fā)線程

    本文詳細(xì)講解了Spring事務(wù)處理Transactional,鎖同步和并發(fā)線程。對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-12-12
  • Spring boot中PropertySource注解的使用方法詳解

    Spring boot中PropertySource注解的使用方法詳解

    這篇文章主要給大家介紹了關(guān)于Spring boot中PropertySource注解的使用方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用Spring boot具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧。
    2017-12-12
  • SpringBoot?整合?ElasticSearch操作各種高級(jí)查詢搜索

    SpringBoot?整合?ElasticSearch操作各種高級(jí)查詢搜索

    這篇文章主要介紹了SpringBoot?整合?ES?進(jìn)行各種高級(jí)查詢搜索的實(shí)踐記錄,本文主要圍繞?SpringBoot?整合?ElasticSearch?進(jìn)行各種高級(jí)查詢的介紹,需要的朋友可以參考下
    2022-06-06

最新評(píng)論