真实的国产乱ⅩXXX66竹夫人,五月香六月婷婷激情综合,亚洲日本VA一区二区三区,亚洲精品一区二区三区麻豆

成都創(chuàng)新互聯(lián)網(wǎng)站制作重慶分公司

怎么優(yōu)化Java線程池

今天小編給大家分享一下怎么優(yōu)化Java線程池的相關(guān)知識點,內(nèi)容詳細(xì),邏輯清晰,相信大部分人都還太了解這方面的知識,所以分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后有所收獲,下面我們一起來了解一下吧。

創(chuàng)新互聯(lián)建站主營平陸網(wǎng)站建設(shè)的網(wǎng)絡(luò)公司,主營網(wǎng)站建設(shè)方案,重慶App定制開發(fā),平陸h5小程序定制開發(fā)搭建,平陸網(wǎng)站營銷推廣歡迎平陸等地區(qū)企業(yè)咨詢

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

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

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

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

  • 移除線程池的線程預(yù)熱功能。因為線程預(yù)熱會極大的耗費內(nèi)存,當(dāng)我們不用線程池時也會一直在運行狀態(tài)。

  • 換來的是在調(diào)用execute方法添加任務(wù)時通過檢查workers線程集合目前的大小與corePoolSize的值去比較,再通過new MyWorker()去創(chuàng)建添加線程到線程池,這樣好處就是當(dāng)我們創(chuàng)建線程池如果不使用的話則對當(dāng)前內(nèi)存沒有一點影響,當(dāng)使用了才會創(chuàng)建線程并放入線程池中進(jìn)行復(fù)用。

線程池構(gòu)造器
public MyThreadPoolExecutor(){
        this(5,new ArrayBlockingQueue<>(10), Executors.defaultThreadFactory(),defaultHandle);
    }
    public MyThreadPoolExecutor(int corePoolSize, BlockingQueue waitingQueue,ThreadFactory threadFactory) {
        this(corePoolSize,waitingQueue,threadFactory,defaultHandle);
    }
    public MyThreadPoolExecutor(int corePoolSize, BlockingQueue 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)部實現(xiàn)類

/**
     * 實現(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ù),此時就有位置當(dāng)新任務(wù)了
                threadPoolExecutor.execute(runnable); //把新任務(wù)加入到隊列中
            }
        }
    }
    //由調(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()

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

手寫線程池源碼

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 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); //線程編號
    private static volatile int corePoolSize; //核心線程數(shù)
    private final HashSet workers; //工作線程
    private final BlockingQueue waitingQueue; //等待隊列
    private static final String THREADPOOL_NAME="MyThread-Pool-";//線程名稱
    private volatile boolean isRunning=true; //是否運行
    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 waitingQueue,ThreadFactory threadFactory) {
        this(corePoolSize,waitingQueue,threadFactory,defaultHandle);
    }
    public MyThreadPoolExecutor(int corePoolSize, BlockingQueue 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ù)不合法");
        }
    }
    /**
     * 實現(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ù),此時就有位置當(dāng)新任務(wù)了
                threadPoolExecutor.execute(runnable); //把新任務(wù)加入到隊列中
            }
        }
    }
    //由調(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就是我們每一個線程對象
     */
    private final class MyWorker implements Runnable{

        final Thread thread; //為每個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的隊列大小為0(也就是無任務(wù)了),會優(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時則調(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() getWaitingQueue() {
        return this.waitingQueue;
    }
}
線程池測試類
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();




  }
}

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

以上就是“怎么優(yōu)化Java線程池”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家閱讀完這篇文章都有很大的收獲,小編每天都會為大家更新不同的知識,如果還想學(xué)習(xí)更多的知識,請關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。


文章標(biāo)題:怎么優(yōu)化Java線程池
文章出自:http://weahome.cn/article/pgiies.html

其他資訊

在線咨詢

微信咨詢

電話咨詢

028-86922220(工作日)

18980820575(7×24)

提交需求

返回頂部