Java線程池

一、線程池簡介

線程的使用在Java中占有重要的地位,尤其是在執(zhí)行耗時操作(Java網(wǎng)絡(luò)編程)和異步訪問(SWT中更新界面元素)時顯得格外重要。線程雖然方便,但當(dāng)需要同時執(zhí)行大量的線程操作和特定的異步訪問時,通過為每一個新任務(wù)單獨(dú)新開線程就會造成大量的資源浪費(fèi),而且對同一類任務(wù)的多線程不能做到統(tǒng)一的管理,所以就有了多線程的技術(shù)。
  多線程技術(shù)主要解決處理器單元內(nèi)多個線程執(zhí)行的問題,它可以顯著減少處理器單元的閑置時間,增加處理器單元的吞吐能力。

二、Java線程池

線程池的作用:

1、限制系統(tǒng)中執(zhí)行線程的數(shù)量

線程池能夠基于當(dāng)前系統(tǒng)運(yùn)行環(huán)境,通過自動或者手動的方式調(diào)整系統(tǒng)中運(yùn)行線程的數(shù)量,從而達(dá)到節(jié)約系統(tǒng)資源的目的。設(shè)置線程池的數(shù)量可以防止程序無限制的開啟線程而造成的資源浪費(fèi),任務(wù)少的時候放入線程池中執(zhí)行,任務(wù)超過線程池?cái)?shù)量限制時,排隊(duì)等待。一個任務(wù)執(zhí)行完畢后會從排隊(duì)任務(wù)重取出任務(wù)放入線程池中執(zhí)行,也就是說當(dāng)一個新任務(wù)到來時,如果線程池未滿則執(zhí)行新任務(wù),如果線程池已滿就需進(jìn)入等待隊(duì)列直到有空閑的線程池資源。

2、對線程的統(tǒng)一管理

開發(fā)過程中會對多個相同或者相似的任務(wù)統(tǒng)一處理的情況,線程池可以對線程統(tǒng)一管理,比如:喚醒線程池中所有的線程,銷毀所有的線程。

Java內(nèi)置的線程池:

Java線程池的頂級接口為Executor,但一般使用較多的接口為ExecutorService,ExecutorService類中含有更多的對線程池的操作。

方法 描述
isShutDown() 如果此執(zhí)行程序已關(guān)閉,則返回 true。
isTerminated() 如果關(guān)閉后所有任務(wù)都已完成,則返回 true。
shutdown() 啟動一次順序關(guān)閉,執(zhí)行以前提交的任務(wù),但不接受新任務(wù)。
shutdownNow() 試圖停止所有正在執(zhí)行的活動任務(wù),暫停處理正在等待的任務(wù),并返回等待執(zhí)行的任務(wù)列表。
submit(task) 提交一個 Runnable 任務(wù)用于執(zhí)行,并返回一個表示該任務(wù)的 Future。

ExecutorService類中常用的方法:

方法 描述
isShutDown() 如果此執(zhí)行程序已關(guān)閉,則返回 true。
isTerminated() 如果關(guān)閉后所有任務(wù)都已完成,則返回 true。
shutdown() 啟動一次順序關(guān)閉,執(zhí)行以前提交的任務(wù),但不接受新任務(wù)。
shutdownNow() 試圖停止所有正在執(zhí)行的活動任務(wù),暫停處理正在等待的任務(wù),并返回等待執(zhí)行的任務(wù)列表。
submit(task) 提交一個 Runnable 任務(wù)用于執(zhí)行,并返回一個表示該任務(wù)的 Future。

為方便創(chuàng)建線程池Executors類中提供一些靜態(tài)方法,用于快速創(chuàng)建線程池。

  1. newCachedThreadPool
      創(chuàng)建一個可緩存線程池,如果線程池大小超過處理需要,可靈活回收空閑線程,若無可回收線程,則創(chuàng)建線程。此線程池不會對線程池大小限制(但可以指定初始線程池的大小),線程池大小完全依賴于JVM空間的限制。
  2. **newFixedThreadPool **
      創(chuàng)建一個定長線程池,可控制線程最大并發(fā)數(shù),線程池一旦達(dá)到最大限制,超出的線程會在隊(duì)列中等待。
  3. **newScheduledThreadPool **
      創(chuàng)建一個定長線程池,它可安排在給定延遲后運(yùn)行命令或者定期地執(zhí)行。
  4. **newSingleThreadExecutor **
      創(chuàng)建一個單線程化的線程池,它只會用唯一的工作線程來執(zhí)行任務(wù),保證所有任務(wù)按照指定順序(FIFO, LIFO, 優(yōu)先級)執(zhí)行。
      
    newCachedThreadPool測試代碼:
public class NewCachedThreadPoolTest {
    public static void main(String[] args) {
        ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
        for (int i = 0; i < 10; i++) {
            final int index = i;
            try {
                Thread.sleep(index * 1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            cachedThreadPool.execute(new Runnable() {
                public void run() {
                    System.out.println(index);
                }
            });
        }
    }
}

當(dāng)執(zhí)行第二個任務(wù)時第一個任務(wù)已經(jīng)完成,會復(fù)用執(zhí)行第一個任務(wù)的線程,而不用每次新建線程。
  
newFixedThreadPool 測試代碼:

public class FixedThreadPoolTest {
    public static void main(String[] args) {
        //創(chuàng)建一個可重用固定線程數(shù)的線程池
        ExecutorService pool = Executors.newFixedThreadPool(2);
        //創(chuàng)建實(shí)現(xiàn)了Runnable接口對象,Thread對象當(dāng)然也實(shí)現(xiàn)了Runnable接口
        Thread t1 = new MyThread();
        Thread t2 = new MyThread();
        Thread t3 = new MyThread();
        Thread t4 = new MyThread();
        Thread t5 = new MyThread();
        //將線程放入池中進(jìn)行執(zhí)行
        pool.execute(t1);
        pool.execute(t2);
        pool.execute(t3);
        pool.execute(t4);
        pool.execute(t5);
        //關(guān)閉線程池
        pool.shutdown();
    }
}

輸出結(jié)果:

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

newScheduledThreadPool 測試代碼:


public class ScheduledThreadPoolExecutorTest {
    public static void main(String[] args) {
        ScheduledThreadPoolExecutor exec = new ScheduledThreadPoolExecutor(1);
        exec.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                System.out.println("================");
            }
        }, 1000, 5000, TimeUnit.MILLISECONDS);
        exec.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                System.out.println(System.nanoTime());
            }
        }, 1000, 2000, TimeUnit.MILLISECONDS);
    }
}

輸出結(jié)果:


================
41070644908191
41072644693809
41074645495462
================
41076644808412
41078644896218
================
41080645104328
41082645027356
41084645111170
================
41086645135117
41088645164196

newScheduledThreadPool 測試代碼:


public class SingleThreadExecutorTest
 {
    public static void main(String[] args) {

        ExecutorService pool = Executors.newSingleThreadExecutor();

        Thread t1 = new MyThread();
        Thread t2 = new MyThread();
        Thread t3 = new MyThread();
        Thread t4 = new MyThread();
        Thread t5 = new MyThread();

        pool.execute(t1);
        pool.execute(t2);
        pool.execute(t3);
        pool.execute(t4);
        pool.execute(t5);
        // 關(guān)閉線程池
        pool.shutdown();
    }
}

輸出結(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í)行。。。

每種線程池都會有特定的使用場景,上述四種線程池能滿足大部分的需求。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容