欧美成人午夜免费全部完,亚洲午夜福利精品久久,а√最新版在线天堂,另类亚洲综合区图片小说区,亚洲欧美日韩精品色xxx

扣丁學(xué)堂Java培訓(xùn)之四種常用線程池詳細(xì)介紹

2019-03-12 15:05:10 1900瀏覽

今天扣丁學(xué)堂Java培訓(xùn)老師給大家介紹一下關(guān)于Java四種常用線程池的詳細(xì)介紹,希望對同學(xué)們學(xué)習(xí)Java開發(fā)有所幫助,下面我們一起來看一下吧。



一.線程池簡介

1.線程池的概念:

線程池就是首先創(chuàng)建一些線程,它們的集合稱為線程池。使用線程池可以很好地提高性能,線程池在系統(tǒng)啟動時即創(chuàng)建大量空閑的線程,程序?qū)⒁粋€任務(wù)傳給線程池,線程池就會啟動一條線程來執(zhí)行這個任務(wù),執(zhí)行結(jié)束以后,該線程并不會死亡,而是再次返回線程池中成為空閑狀態(tài),等待執(zhí)行下一個任務(wù)。

2.線程池的工作機(jī)制

2.1在線程池的編程模式下,任務(wù)是提交給整個線程池,而不是直接提交給某個線程,線程池在拿到任務(wù)后,就在內(nèi)部尋找是否有空閑的線程,如果有,則將任務(wù)交給某個空閑的線程。

2.2一個線程同時只能執(zhí)行一個任務(wù),但可以同時向一個線程池提交多個任務(wù)。

3.使用線程池的原因:

多線程運(yùn)行時間,系統(tǒng)不斷的啟動和關(guān)閉新線程,成本非常高,會過渡消耗系統(tǒng)資源,以及過渡切換線程的危險,從而可能導(dǎo)致系統(tǒng)資源的崩潰。這時,線程池就是最好的選擇了。

二.四種常見的線程池詳解

1.線程池的返回值ExecutorService簡介:

ExecutorService是Java提供的用于管理線程池的類。該類的兩個作用:控制線程數(shù)量和重用線程

2.具體的4種常用的線程池實(shí)現(xiàn)如下:(返回值都是ExecutorService)

2.1Executors.newCacheThreadPool():可緩存線程池,先查看池中有沒有以前建立的線程,如果有,就直接使用。如果沒有,就建一個新的線程加入池中,緩存型池子通常用于執(zhí)行一些生存期很短的異步型任務(wù)

示例代碼:

package com.study.test;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadPoolExecutorTest {
  public static void main(String[] args) {
   //創(chuàng)建一個可緩存線程池
   ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
   for (int i = 0; i < 10; i++) {
     try {
       //sleep可明顯看到使用的是線程池里面以前的線程,沒有創(chuàng)建新的線程
       Thread.sleep(1000);
     } catch (InterruptedException e) {
       e.printStackTrace();
      }
     cachedThreadPool.execute(new Runnable() {
       public void run() {
    //打印正在執(zhí)行的緩存線程信息
          System.out.println(Thread.currentThread().getName()+"正在被執(zhí)行");
       }
      });
    }
  }
}

輸出結(jié)果:

pool-1-thread-1正在被執(zhí)行
pool-1-thread-1正在被執(zhí)行
pool-1-thread-1正在被執(zhí)行
pool-1-thread-1正在被執(zhí)行
pool-1-thread-1正在被執(zhí)行
pool-1-thread-1正在被執(zhí)行
pool-1-thread-1正在被執(zhí)行
pool-1-thread-1正在被執(zhí)行
pool-1-thread-1正在被執(zhí)行
pool-1-thread-1正在被執(zhí)行

線程池為無限大,當(dāng)執(zhí)行當(dāng)前任務(wù)時上一個任務(wù)已經(jīng)完成,會復(fù)用執(zhí)行上一個任務(wù)的線程,而不用每次新建線程

2.2Executors.newFixedThreadPool(intn):創(chuàng)建一個可重用固定個數(shù)的線程池,以共享的無界隊列方式來運(yùn)行這些線程。

示例代碼:

package com.study.test;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadPoolExecutorTest {
 public static void main(String[] args) {
    //創(chuàng)建一個可重用固定個數(shù)的線程池
    ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);
    for (int i = 0; i < 10; i++) {
     fixedThreadPool.execute(new Runnable() {
        public void run() {
          try {
           //打印正在執(zhí)行的緩存線程信息
           System.out.println(Thread.currentThread().getName()+"正在被執(zhí)行");
           Thread.sleep(2000);
         } catch (InterruptedException e) {
           e.printStackTrace();
          }
        }
     });
    }
  }
}

輸出結(jié)果:

pool-1-thread-1正在被執(zhí)行
pool-1-thread-2正在被執(zhí)行
pool-1-thread-3正在被執(zhí)行
pool-1-thread-1正在被執(zhí)行
pool-1-thread-2正在被執(zhí)行
pool-1-thread-3正在被執(zhí)行
pool-1-thread-1正在被執(zhí)行
pool-1-thread-2正在被執(zhí)行
pool-1-thread-3正在被執(zhí)行
pool-1-thread-1正在被執(zhí)行

因?yàn)榫€程池大小為3,每個任務(wù)輸出打印結(jié)果后sleep2秒,所以每兩秒打印3個結(jié)果。

定長線程池的大小最好根據(jù)系統(tǒng)資源進(jìn)行設(shè)置。如Runtime.getRuntime().availableProcessors()

2.3Executors.newScheduledThreadPool(intn):創(chuàng)建一個定長線程池,支持定時及周期性任務(wù)執(zhí)行

延遲執(zhí)行示例代碼:

package com.study.test;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class ThreadPoolExecutorTest {
  public static void main(String[] args) {
    //創(chuàng)建一個定長線程池,支持定時及周期性任務(wù)執(zhí)行——延遲執(zhí)行
    ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);
    //延遲1秒執(zhí)行
    scheduledThreadPool.schedule(new Runnable() {
      public void run() {
        System.out.println("延遲1秒執(zhí)行");
      }
    }, 1, TimeUnit.SECONDS);
   }
}

輸出結(jié)果:

延遲1秒執(zhí)行

定期執(zhí)行示例代碼:

package com.study.test;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class ThreadPoolExecutorTest {
  public static void main(String[] args) {
    //創(chuàng)建一個定長線程池,支持定時及周期性任務(wù)執(zhí)行——定期執(zhí)行
    ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);
    //延遲1秒后每3秒執(zhí)行一次
    scheduledThreadPool.scheduleAtFixedRate(new Runnable() {
       public void run() {
        System.out.println("延遲1秒后每3秒執(zhí)行一次");
      }
    }, 1, 3, TimeUnit.SECONDS);
  }
}

輸出結(jié)果:

延遲1秒后每3秒執(zhí)行一次
延遲1秒后每3秒執(zhí)行一次
.............

2.4Executors.newSingleThreadExecutor():創(chuàng)建一個單線程化的線程池,它只會用唯一的工作線程來執(zhí)行任務(wù),保證所有任務(wù)按照指定順序(FIFO,LIFO,優(yōu)先級)執(zhí)行。

示例代碼:

package com.study.test;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class TestThreadPoolExecutor {
  public static void main(String[] args) {
    //創(chuàng)建一個單線程化的線程池
    ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
    for (int i = 0; i < 10; i++) {
      final int index = i;
       singleThreadExecutor.execute(new Runnable() {
        public void run() {
          try {
            //結(jié)果依次輸出,相當(dāng)于順序執(zhí)行各個任務(wù)
            System.out.println(Thread.currentThread().getName()+"正在被執(zhí)行,打印的值是:"+index);
            Thread.sleep(1000);
          } catch (InterruptedException e) {
             e.printStackTrace();
          }
        }
       });
    }
   }
}

輸出結(jié)果:

pool-1-thread-1正在被執(zhí)行,打印的值是:0
pool-1-thread-1正在被執(zhí)行,打印的值是:1
pool-1-thread-1正在被執(zhí)行,打印的值是:2
pool-1-thread-1正在被執(zhí)行,打印的值是:3
pool-1-thread-1正在被執(zhí)行,打印的值是:4
pool-1-thread-1正在被執(zhí)行,打印的值是:5
pool-1-thread-1正在被執(zhí)行,打印的值是:6
pool-1-thread-1正在被執(zhí)行,打印的值是:7
pool-1-thread-1正在被執(zhí)行,打印的值是:8
pool-1-thread-1正在被執(zhí)行,打印的值是:9

三.緩沖隊列BlockingQueue和自定義線程池ThreadPoolExecutor

1.緩沖隊列BlockingQueue簡介:

BlockingQueue是雙緩沖隊列。BlockingQueue內(nèi)部使用兩條隊列,允許兩個線程同時向隊列一個存儲,一個取出操作。在保證并發(fā)安全的同時,提高了隊列的存取效率。

2.常用的幾種BlockingQueue:

ArrayBlockingQueue(inti):規(guī)定大小的BlockingQueue,其構(gòu)造必須指定大小。其所含的對象是FIFO順序排序的。

LinkedBlockingQueue()或者(inti):大小不固定的BlockingQueue,若其構(gòu)造時指定大小,生成的BlockingQueue有大小限制,不指定大小,其大小有Integer.MAX_VALUE來決定。其所含的對象是FIFO順序排序的。

PriorityBlockingQueue()或者(inti):類似于LinkedBlockingQueue,但是其所含對象的排序不是FIFO,而是依據(jù)對象的自然順序或者構(gòu)造函數(shù)的Comparator決定。

SynchronizedQueue():特殊的BlockingQueue,對其的操作必須是放和取交替完成。

3.自定義線程池(ThreadPoolExecutor和BlockingQueue連用):

自定義線程池,可以用ThreadPoolExecutor類創(chuàng)建,它有多個構(gòu)造方法來創(chuàng)建線程池。

常見的構(gòu)造函數(shù):ThreadPoolExecutor(intcorePoolSize,intmaximumPoolSize,longkeepAliveTime,TimeUnitunit,BlockingQueue<Runnable>workQueue)

示例代碼:

package com.study.test;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
class TempThread implements Runnable {
  @Override
  public void run() {
    // 打印正在執(zhí)行的緩存線程信息
    System.out.println(Thread.currentThread().getName() + "正在被執(zhí)行");
     try {
      // sleep一秒保證3個任務(wù)在分別在3個線程上執(zhí)行
      Thread.sleep(1000);
     } catch (InterruptedException e) {
       e.printStackTrace();
    }
   } 
}
public class TestThreadPoolExecutor {
  public static void main(String[] args) {
    // 創(chuàng)建數(shù)組型緩沖等待隊列
    BlockingQueue<Runnable> bq = new ArrayBlockingQueue<Runnable>(10);
    // ThreadPoolExecutor:創(chuàng)建自定義線程池,池中保存的線程數(shù)為3,允許最大的線程數(shù)為6
    ThreadPoolExecutor tpe = new ThreadPoolExecutor(3, 6, 50, TimeUnit.MILLISECONDS, bq);
    // 創(chuàng)建3個任務(wù)
     Runnable t1 = new TempThread();
     Runnable t2 = new TempThread();
     Runnable t3 = new TempThread();
     // Runnable t4 = new TempThread();
     // Runnable t5 = new TempThread();
     // Runnable t6 = new TempThread(); 
     // 3個任務(wù)在分別在3個線程上執(zhí)行
     tpe.execute(t1);
     tpe.execute(t2);
     tpe.execute(t3);
     // tpe.execute(t4);
     // tpe.execute(t5);
     // tpe.execute(t6); 
     // 關(guān)閉自定義線程池
     tpe.shutdown();
   }
}

輸出結(jié)果:

pool-1-thread-1正在被執(zhí)行
pool-1-thread-2正在被執(zhí)行
pool-1-thread-3正在被執(zhí)行

以上就是關(guān)于扣丁學(xué)堂Java培訓(xùn)之四種常用線程池詳細(xì)介紹的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,想要了解更多關(guān)于Java開發(fā)方面內(nèi)容的小伙伴,請關(guān)注扣丁學(xué)堂Java培訓(xùn)官網(wǎng)、微信等平臺,扣丁學(xué)堂IT職業(yè)在線學(xué)習(xí)教育平有專業(yè)的Java講師為您指導(dǎo),此外扣丁學(xué)堂老師精心推出的Java視頻教程定能讓你快速掌握J(rèn)ava從入門到精通開發(fā)實(shí)戰(zhàn)技能。扣丁學(xué)堂Java技術(shù)交流群:670348138。

扣丁學(xué)堂微信公眾號


【關(guān)注微信公眾號獲取更多學(xué)習(xí)資料】



查看更多關(guān)于“Java開發(fā)資訊”的相關(guān)文章>>

標(biāo)簽: Java培訓(xùn) Java視頻教程 Java多線程 Java面試題 Java學(xué)習(xí)視頻 Java開發(fā)

熱門專區(qū)

暫無熱門資訊

課程推薦

微信
微博
15311698296

全國免費(fèi)咨詢熱線

郵箱:codingke@1000phone.com

官方群:148715490

北京千鋒互聯(lián)科技有限公司版權(quán)所有   北京市海淀區(qū)寶盛北里西區(qū)28號中關(guān)村智誠科創(chuàng)大廈4層
京ICP備2021002079號-2   Copyright ? 2017 - 2022
返回頂部 返回頂部