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

學(xué)生視角手把手帶你寫Java?線程池初版

 更新時間:2022年03月21日 11:16:08   作者:摸魚打醬油  
作者是一個來自河源的大三在校生,以下筆記都是作者自學(xué)之路的一些淺薄經(jīng)驗,如有錯誤請指正,將來會不斷的完善筆記,幫助更多的Java愛好者入門

Java手寫線程池(第一代)

經(jīng)常使用線程池,故今天突發(fā)奇想,手寫一個線程池,會有很多不足,請多多寬容。因為這也是第一代的版本,后續(xù)會更完善。

手寫線程池-定義參數(shù)

	private final AtomicInteger taskcount=new AtomicInteger(0);
    private final AtomicInteger threadNumber=new AtomicInteger(0);
    private volatile int corePoolSize; 
    private final Set<MyThreadPoolExecutor.MyWorker> workers; 
    private final BlockingQueue<Runnable> waitingQueue; 
    private final String THREADPOOL_NAME="MyThread-Pool-";
    private volatile boolean isRunning=true; 
    private volatile boolean STOPNOW=false; 
    private final ThreadFactory threadFactory; 
  • taskcount:執(zhí)行任務(wù)次數(shù)
  • threadNumber:線程編號,從0開始依次遞增。
  • corePoolSize:核心線程數(shù)
  • workers:工作線程
  • waitingQueue:等待隊列
  • THREADPOOL_NAME:線程名稱
  • isRunning:是否運(yùn)行
  • STOPNOW:是否立刻停止
  • threadFactory:線程工廠

手寫線程池-構(gòu)造器

    public MyThreadPoolExecutor(int corePoolSize, BlockingQueue<Runnable> waitingQueue,ThreadFactory threadFactory) {
        this.corePoolSize=corePoolSize;
        this.workers=new HashSet<>(corePoolSize);
        this.waitingQueue=waitingQueue;
        this.threadFactory=threadFactory;
        //線程預(yù)熱
        for (int i = 0; i < corePoolSize; i++) {
            new MyWorker();
        }
    }

該構(gòu)造器作用:

1:對參數(shù)進(jìn)行賦值。

2:線程預(yù)熱。根據(jù)corePoolSize的大小來調(diào)用MyWorker的構(gòu)造器。我們可以看看MyWorker構(gòu)造器做了什么。

	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);
        }
  • MyWorker構(gòu)造器通過線程工廠對當(dāng)前對象生成Thread;
  • 并設(shè)置線程名為:MyThread-Pool-自增線程編號;
  • 然后調(diào)用線程的start方法啟動線程;
  • 最后存放在workers這個Set集合中,這樣就可以實現(xiàn)線程復(fù)用了。

手寫線程池-默認(rèn)構(gòu)造器

	public MyThreadPoolExecutor(){
        this(5,new ArrayBlockingQueue<>(10), Executors.defaultThreadFactory());
    }
  • 默認(rèn)構(gòu)造器的賦初始值:
  • corePoolSize:5
  • waitingQueue:new ArrayBlockingQueue<>(10),長度為10的有限阻塞隊列
  • threadFactory:Executors.defaultThreadFactory()

手寫線程池-execute方法

	public boolean execute(Runnable runnable)
    {
        return waitingQueue.offer(runnable);
    }
  • 本質(zhì)上其實就是把Runnable(任務(wù))放到waitingQueue中。

手寫線程池-處理任務(wù)

	   @Override
        public void run() {
            //循環(huán)接收任務(wù)
                while (true)
                {
                    if((!isRunning&&waitingQueue.size()==0)||STOPNOW)
                    {
                        break;
                    }else {
                        Runnable runnable = waitingQueue.poll();
                        if(runnable!=null){
                            runnable.run();
                            System.out.println("task==>"+taskcount.incrementAndGet());
                        }
                    }
                }
        }

本質(zhì)上就是一個死循環(huán)接收任務(wù),退出條件如下:

  • 優(yōu)雅的退出。當(dāng)isRunning為false并且waitingQueue的隊列大小為0(也就是無任務(wù)了)
  • 暴力退出。當(dāng)STOPNOW為true,則說明調(diào)用了shutdownNow方法
  • else語句塊會不斷取任務(wù),當(dāng)任務(wù)!=null時則調(diào)用run方法處理任務(wù)

手寫線程池-優(yōu)雅關(guān)閉線程池

	public void shutdown()
    {
        this.isRunning=false;
    }

手寫線程池-暴力關(guān)閉線程池

	public void shutdownNow()
    {
        this.STOPNOW=true;
    }

手寫線程池-源代碼

  • 手寫線程池類的源代碼
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;

/**
 * 線程池類
 * @author 游政杰
 */
public class MyThreadPoolExecutor {

    private final AtomicInteger taskcount=new AtomicInteger(0);//執(zhí)行任務(wù)次數(shù)
    private final AtomicInteger threadNumber=new AtomicInteger(0); //線程編號
    private volatile int corePoolSize; //核心線程數(shù)
    private final Set<MyThreadPoolExecutor.MyWorker> workers; //工作線程
    private final BlockingQueue<Runnable> waitingQueue; //等待隊列
    private final String THREADPOOL_NAME="MyThread-Pool-";//線程名稱
    private volatile boolean isRunning=true; //是否運(yùn)行
    private volatile boolean STOPNOW=false; //是否立刻停止
    private final ThreadFactory threadFactory; //線程工廠

    public MyThreadPoolExecutor(){
        this(5,new ArrayBlockingQueue<>(10), Executors.defaultThreadFactory());
    }

    public MyThreadPoolExecutor(int corePoolSize, BlockingQueue<Runnable> waitingQueue,ThreadFactory threadFactory) {
        this.corePoolSize=corePoolSize;
        this.workers=new HashSet<>(corePoolSize);
        this.waitingQueue=waitingQueue;
        this.threadFactory=threadFactory;
        //線程預(yù)熱
        for (int i = 0; i < corePoolSize; i++) {
            new MyWorker();
        }
    }

    /**
     * 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);
        }

        @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());
                        }
                    }
                }
        }
    }

    public boolean execute(Runnable runnable)
    {
        return waitingQueue.offer(runnable);
    }
    //優(yōu)雅的關(guān)閉
    public void shutdown()
    {
        this.isRunning=false;
    }
    //暴力關(guān)閉
    public void shutdownNow()
    {
        this.STOPNOW=true;
    }
}
  • 測試使用手寫線程池代碼
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());

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

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

      }

      myThreadPoolExecutor.shutdown();

//      myThreadPoolExecutor.shutdownNow();



  }
}

問題

為什么自定義線程池的execute執(zhí)行的任務(wù)有時會變少?

那是因為waitingQueue滿了放不下任務(wù)了,導(dǎo)致任務(wù)被丟棄,相當(dāng)于DiscardPolicy拒絕策略

解決辦法有:

1:設(shè)置最大線程數(shù),自動對線程池擴(kuò)容。

2:調(diào)大waitingQueue的容量capacity

最后:因為這是我手寫的線程池的初代版本,基本實現(xiàn)線程池的復(fù)用功能,然而還有很多未完善,將來會多出幾篇完善后的文章,對目前手寫的線程池進(jìn)行升級。

后續(xù)還會繼續(xù)出關(guān)于作者手寫Spring框架,手寫Tomcat等等框架的博文?。。。。?/p>

到此這篇關(guān)于學(xué)生視角手把手帶你寫Java 線程池的文章就介紹到這了,更多相關(guān)Java 線程池內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Spring Boot 項目搭建教程及注解

    Spring Boot 項目搭建教程及注解

    下面小編就為大家?guī)硪黄猄pring Boot 項目搭建教程及注解。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-09-09
  • Spring AOP快速入門及開發(fā)步驟

    Spring AOP快速入門及開發(fā)步驟

    Spring AOP(面向切面編程)核心概念包括切面(Aspect)、連接點(diǎn)(JoinPoint)、切點(diǎn)(Pointcut)、通知(Advice)等,通過在不改變原代碼的情況下,對方法進(jìn)行增強(qiáng),實現(xiàn)了代碼的解耦和功能擴(kuò)展,本文帶來大家掌握Spring 中 AOP 的開發(fā)步驟,感興趣的朋友一起看看吧
    2024-10-10
  • java使用CountDownLatch等待多線程全部執(zhí)行完成

    java使用CountDownLatch等待多線程全部執(zhí)行完成

    這篇文章主要為大家詳細(xì)介紹了使用CountDownLatch等待多線程全部執(zhí)行完成,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-10-10
  • 深入淺析hbase的優(yōu)點(diǎn)

    深入淺析hbase的優(yōu)點(diǎn)

    本文講述了HBase的特征和它的優(yōu)點(diǎn),并簡要回顧了行鍵設(shè)計的重點(diǎn)之處,它還向你展示了如何在本地配置HBase環(huán)境,使用命令創(chuàng)建表、插入數(shù)據(jù)、檢索指定行以及最后如何進(jìn)行scan操作,感興趣的朋友一起看看吧
    2017-09-09
  • Java數(shù)據(jù)庫操作庫DButils類的使用方法與實例詳解

    Java數(shù)據(jù)庫操作庫DButils類的使用方法與實例詳解

    這篇文章主要介紹了JDBC數(shù)據(jù)庫操作庫DButils類的使用方法詳解,需要的朋友可以參考下
    2020-02-02
  • 詳解Eclipse Validating緩慢的優(yōu)化

    詳解Eclipse Validating緩慢的優(yōu)化

    這篇文章主要介紹了詳解Eclipse Validating緩慢的優(yōu)化,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-03-03
  • ZooKeeper入門教程一簡介與核心概念

    ZooKeeper入門教程一簡介與核心概念

    本文是ZooKeeper入門系列教程,涵蓋ZooKeeper核心內(nèi)容,通過實例和大量圖表,結(jié)合實戰(zhàn),幫助學(xué)習(xí)者理解和運(yùn)用,有需要的朋友可以借鑒參考下,希望能夠有所幫助
    2022-01-01
  • Java實現(xiàn)threadLocal線程池獲取

    Java實現(xiàn)threadLocal線程池獲取

    本文主要介紹了Java實現(xiàn)threadLocal線程池獲取,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-07-07
  • java加載屬性配置properties文件的方法

    java加載屬性配置properties文件的方法

    這篇文章主要介紹了java加載屬性配置properties文件的方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-03-03
  • 詳解Java中的final關(guān)鍵字

    詳解Java中的final關(guān)鍵字

    子類可以在父類的基礎(chǔ)上改寫父類內(nèi)容,為了避免這種隨意改寫的情況,Java提供了final 關(guān)鍵字,用于修飾不可改變內(nèi)容。本文就來詳細(xì)說說final關(guān)鍵字的使用,需要的可以參考一下
    2022-10-10

最新評論

邛崃市| 开远市| 高阳县| 屯留县| 南丹县| 沙河市| 咸丰县| 桐梓县| 嘉义县| 大英县| 黑水县| 偏关县| 海阳市| 遂昌县| 高安市| 开封市| 南康市| 邻水| 汉沽区| 湟源县| 云浮市| 剑河县| 隆回县| 宜阳县| 安国市| 修水县| 城固县| 株洲县| 永德县| 贵南县| 泽州县| 乌海市| 静乐县| 迁安市| 岐山县| 青河县| 南涧| 甘谷县| 邮箱| 盘锦市| 海伦市|