多线程线程池的基本创建,使用方法
生活随笔
收集整理的這篇文章主要介紹了
多线程线程池的基本创建,使用方法
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
import java.util.concurrent.*;/*** 多線程線程池的基本創(chuàng)建,使用方法** @author silence*/
public class Silence {public static void main(String[] args) {//創(chuàng)建一個(gè)線程池 最大線程數(shù)量20 核心線程15//如果提交了超過(guò)15 不超過(guò)20的任務(wù),會(huì)創(chuàng)建臨時(shí)線程。//臨時(shí)線程超過(guò) 60秒會(huì)被銷毀//如果提交任務(wù)數(shù)量,超過(guò) 最大線程數(shù)量+排隊(duì)數(shù)量, 會(huì)拋出異常ThreadPoolExecutor thread = new ThreadPoolExecutor(//核心線程5,//最大線程數(shù)量10,//等待時(shí)間60,//等待時(shí)間的單位(秒)TimeUnit.SECONDS,//阻塞隊(duì)列,排隊(duì)的數(shù)量new ArrayBlockingQueue<>(10),//默認(rèn)線程工廠Executors.defaultThreadFactory(),//超出任務(wù)的拒絕策略new ThreadPoolExecutor.AbortPolicy());//提交十個(gè)線程任務(wù),并讓他暫時(shí)阻塞在哪里for (int i = 0; i < 8; i++) {//判斷線程池有沒(méi)有提交滿while (true) {//正在執(zhí)行的線程數(shù)量int activeCount = thread.getActiveCount();//最大線程數(shù)int maximumPoolSize = thread.getMaximumPoolSize();//如果線程池沒(méi)滿就提交//提交線程任務(wù)if (activeCount < maximumPoolSize) {thread.submit(() -> {System.out.println("線程提交");try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}});break;}}}//關(guān)閉線程池thread.shutdown();//線程池關(guān)閉后,已提交的線程任務(wù)。可以繼續(xù)執(zhí)行,但不能提交新任務(wù)//可以在確定沒(méi)有線程任務(wù)提交之后關(guān)閉/* thread.submit(()->{System.out.println("55");});*///返回正在執(zhí)行任務(wù)的線程的大概數(shù)量。int activeCount = thread.getActiveCount();System.out.println("返回正在執(zhí)行任務(wù)的線程的大概數(shù)量:" + activeCount);//返回允許的最大線程數(shù)。
/* int maximumPoolSize = thread.getMaximumPoolSize();System.out.println("返回允許的最大線程數(shù):" + maximumPoolSize);*///如果所有任務(wù)在關(guān)閉后完成,則返回 true 。/* boolean terminated = thread.isTerminated();System.out.println("如果所有任務(wù)在關(guān)閉后完成,則返回 true: " + terminated);*///BlockingQueue<Runnable> queue = thread.getQueue();System.out.println("隊(duì)列排隊(duì)的任務(wù)個(gè)數(shù):" + queue.size());}
}
總結(jié)
以上是生活随笔為你收集整理的多线程线程池的基本创建,使用方法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Redmi K50i首曝光:屏幕变为LC
- 下一篇: 判断一个字符串大写小写,和数字出现的次数