欧美一区二区三区老妇人-欧美做爰猛烈大尺度电-99久久夜色精品国产亚洲a-亚洲福利视频一区二区

Java中有哪些常用的線(xiàn)程池

這期內(nèi)容當(dāng)中小編將會(huì)給大家?guī)?lái)有關(guān)Java中有哪些常用的線(xiàn)程池,文章內(nèi)容豐富且以專(zhuān)業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。

創(chuàng)新互聯(lián)為客戶(hù)提供專(zhuān)業(yè)的成都網(wǎng)站設(shè)計(jì)、做網(wǎng)站、成都外貿(mào)網(wǎng)站建設(shè)公司、程序、域名、空間一條龍服務(wù),提供基于WEB的系統(tǒng)開(kāi)發(fā). 服務(wù)項(xiàng)目涵蓋了網(wǎng)頁(yè)設(shè)計(jì)、網(wǎng)站程序開(kāi)發(fā)、WEB系統(tǒng)開(kāi)發(fā)、微信二次開(kāi)發(fā)、手機(jī)網(wǎng)站制作設(shè)計(jì)等網(wǎng)站方面業(yè)務(wù)。

1. 線(xiàn)程池的概念:

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

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

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

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

3. 使用線(xiàn)程池的原因:

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

二. 四種常見(jiàn)的線(xiàn)程池詳解

1. 線(xiàn)程池的返回值ExecutorService簡(jiǎn)介:

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

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

2.1 Executors.newCacheThreadPool():可緩存線(xiàn)程池,先查看池中有沒(méi)有以前建立的線(xiàn)程,如果有,就直接使用。如果沒(méi)有,就建一個(gè)新的線(xiàn)程加入池中,緩存型池子通常用于執(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)建一個(gè)可緩存線(xiàn)程池
   ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
   for (int i = 0; i < 10; i++) {
     try {
       //sleep可明顯看到使用的是線(xiàn)程池里面以前的線(xiàn)程,沒(méi)有創(chuàng)建新的線(xiàn)程
       Thread.sleep(1000);
     } catch (InterruptedException e) {
       e.printStackTrace();
      }
     cachedThreadPool.execute(new Runnable() {
       public void run() {
    //打印正在執(zhí)行的緩存線(xiàn)程信息
          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í)行

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

2.2  Executors.newFixedThreadPool(int n):創(chuàng)建一個(gè)可重用固定個(gè)數(shù)的線(xiàn)程池,以共享的無(wú)界隊(duì)列方式來(lái)運(yùn)行這些線(xià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)建一個(gè)可重用固定個(gè)數(shù)的線(xiàn)程池
    ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);
    for (int i = 0; i < 10; i++) {
     fixedThreadPool.execute(new Runnable() {
        public void run() {
          try {
           //打印正在執(zhí)行的緩存線(xiàn)程信息
           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)榫€(xiàn)程池大小為3,每個(gè)任務(wù)輸出打印結(jié)果后sleep 2秒,所以每?jī)擅氪蛴?個(gè)結(jié)果。

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

2.3  Executors.newScheduledThreadPool(int n):創(chuàng)建一個(gè)定長(zhǎng)線(xiàn)程池,支持定時(shí)及周期性任務(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)建一個(gè)定長(zhǎng)線(xiàn)程池,支持定時(shí)及周期性任務(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)建一個(gè)定長(zhǎng)線(xiàn)程池,支持定時(shí)及周期性任務(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.4  Executors.newSingleThreadExecutor():創(chuàng)建一個(gè)單線(xiàn)程化的線(xiàn)程池,它只會(huì)用唯一的工作線(xiàn)程來(lái)執(zhí)行任務(wù),保證所有任務(wù)按照指定順序(FIFO, LIFO, 優(yōu)先級(jí))執(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)建一個(gè)單線(xiàn)程化的線(xiàn)程池
    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í)行各個(gè)任務(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

三. 緩沖隊(duì)列BlockingQueue和自定義線(xiàn)程池ThreadPoolExecutor

1. 緩沖隊(duì)列BlockingQueue簡(jiǎn)介:

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

2. 常用的幾種BlockingQueue:

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

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

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

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

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

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

常見(jiàn)的構(gòu)造函數(shù):ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, 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í)行的緩存線(xiàn)程信息
    System.out.println(Thread.currentThread().getName() + "正在被執(zhí)行");
     try {
      // sleep一秒保證3個(gè)任務(wù)在分別在3個(gè)線(xiàn)程上執(zhí)行
      Thread.sleep(1000);
     } catch (InterruptedException e) {
       e.printStackTrace();
    }
   } 
}
public class TestThreadPoolExecutor {
  public static void main(String[] args) {
    // 創(chuàng)建數(shù)組型緩沖等待隊(duì)列
    BlockingQueue<Runnable> bq = new ArrayBlockingQueue<Runnable>(10);
    // ThreadPoolExecutor:創(chuàng)建自定義線(xiàn)程池,池中保存的線(xiàn)程數(shù)為3,允許最大的線(xiàn)程數(shù)為6
    ThreadPoolExecutor tpe = new ThreadPoolExecutor(3, 6, 50, TimeUnit.MILLISECONDS, bq);
    // 創(chuàng)建3個(gè)任務(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個(gè)任務(wù)在分別在3個(gè)線(xiàn)程上執(zhí)行
     tpe.execute(t1);
     tpe.execute(t2);
     tpe.execute(t3);
     // tpe.execute(t4);
     // tpe.execute(t5);
     // tpe.execute(t6); 
     // 關(guān)閉自定義線(xiàn)程池
     tpe.shutdown();
   }
}

輸出結(jié)果:

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

上述就是小編為大家分享的Java中有哪些常用的線(xiàn)程池了,如果剛好有類(lèi)似的疑惑,不妨參照上述分析進(jìn)行理解。如果想知道更多相關(guān)知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。

網(wǎng)站欄目:Java中有哪些常用的線(xiàn)程池
鏈接URL:http://chinadenli.net/article8/iphhip.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供商城網(wǎng)站建站公司關(guān)鍵詞優(yōu)化網(wǎng)站策劃品牌網(wǎng)站建設(shè)企業(yè)建站

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶(hù)投稿、用戶(hù)轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話(huà):028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)

成都app開(kāi)發(fā)公司