溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

java中如何使用線程池

發(fā)布時間:2021-06-30 17:18:46 來源:億速云 閱讀:174 作者:Leah 欄目:大數(shù)據(jù)

本篇文章給大家分享的是有關(guān)java中如何使用線程池,小編覺得挺實用的,因此分享給大家學(xué)習(xí),希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。

public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                              ThreadFactory threadFactory,
                              RejectedExecutionHandler handler) {
        if (corePoolSize < 0 ||
            maximumPoolSize <= 0 ||
            maximumPoolSize < corePoolSize ||
            keepAliveTime < 0)
            throw new IllegalArgumentException();
        if (workQueue == null || threadFactory == null || handler == null)
            throw new NullPointerException();
        this.acc = System.getSecurityManager() == null ?
                null :
                AccessController.getContext();
        this.corePoolSize = corePoolSize;
        this.maximumPoolSize = maximumPoolSize;
        this.workQueue = workQueue;
        this.keepAliveTime = unit.toNanos(keepAliveTime);
        this.threadFactory = threadFactory;
        this.handler = handler;
    }
	
	構(gòu)造函數(shù)的參數(shù)含義如下:

corePoolSize:指定了線程池中的線程數(shù)量,它的數(shù)量決定了添加的任務(wù)是開辟新的線程去執(zhí)行,還是放到workQueue任務(wù)隊列中去;

maximumPoolSize:指定了線程池中的最大線程數(shù)量,這個參數(shù)會根據(jù)你使用的workQueue任務(wù)隊列的類型,決定線程池會開辟的最大線程數(shù)量;

keepAliveTime:當(dāng)線程池中空閑線程數(shù)量超過corePoolSize時,多余的線程會在多長時間內(nèi)被銷毀;

unit:keepAliveTime的單位

workQueue:任務(wù)隊列,被添加到線程池中,但尚未被執(zhí)行的任務(wù);它一般分為直接提交隊列、有界任務(wù)隊列、無界任務(wù)隊列、優(yōu)先任務(wù)隊列幾種;

threadFactory:線程工廠,用于創(chuàng)建線程,一般用默認(rèn)即可;

handler:拒絕策略;當(dāng)任務(wù)太多來不及處理時,如何拒絕任務(wù);
package com.test;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class TestThreadPool {

	public static void main(String[] args) {
		/**
		 * 線程數(shù)量
		 * 最大數(shù)量 超標(biāo)后會進入隊列、隊列超標(biāo)后觸發(fā)策略
		 * 
		 * ArrayBlockingQueue 有界隊列
		 * LinkedBlockingQueue 無界隊列
		 * SynchronousQueue 同步隊列
		 * 
		 * 執(zhí)行線程超標(biāo)策略 RejectedExecutionHandler
		 * ThreadPoolExecutor.AbortPolicy:丟棄任務(wù)并拋出RejectedExecutionException異常。 
		 * ThreadPoolExecutor.DiscardPolicy:也是丟棄任務(wù),但是不拋出異常。 
		 * ThreadPoolExecutor.DiscardOldestPolicy:丟棄隊列最前面的任務(wù),然后重新嘗試執(zhí)行任務(wù)(重復(fù)此過程)
		 * ThreadPoolExecutor.CallerRunsPolicy:由調(diào)用線程處理該任務(wù)
		 * 自定義
		 * Executors.newCachedThreadPool();        //創(chuàng)建一個緩沖池,緩沖池容量大小為Integer.MAX_VALUE
		 * Executors.newSingleThreadExecutor();   //創(chuàng)建容量為1的緩沖池
		 * Executors.newFixedThreadPool(int);    //創(chuàng)建固定容量大小的緩沖池
		 *
		 */
		ThreadPoolExecutor pool=new ThreadPoolExecutor(5, 5, 1, TimeUnit.SECONDS, new ArrayBlockingQueue(2),new RejectedExecutionHandler() {
			@Override
			public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
			 System.out.println(r+"丟棄了");
			}
		});
		
		for(int i=0;i<7;i++) {
			Runnable run=new TestThread(i);
			pool.execute(run);
		}
		//pool.shutdown();
	}
}

class TestThread implements Runnable {
	private int i;
	
	public TestThread(int i) {
		this.i=i;
	}
	
	@Override
	public void run() {
		try {
			Thread.sleep(100);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println(Thread.currentThread().getName()+" "+i);
	}
}

以上就是java中如何使用線程池,小編相信有部分知識點可能是我們?nèi)粘9ぷ鲿姷交蛴玫降?。希望你能通過這篇文章學(xué)到更多知識。更多詳情敬請關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI