Java簡(jiǎn)單模擬實(shí)現(xiàn)一個(gè)線程池
廢話不多說之間上代碼
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class MyThreadPoolExecutor {
private List<Thread> list=new ArrayList<>();
private BlockingQueue<Runnable> blockingQueue=new ArrayBlockingQueue<>(100);
public MyThreadPoolExecutor(int size) {
for (int i = 0; i < size; i++) {
Thread thread=new Thread(()->{
while (true) {
Runnable runnable= null;
try {
runnable = blockingQueue.take();
runnable.run();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
});
thread.start();
list.add(thread);
}
}
public void submit(Runnable runnable) throws InterruptedException {
blockingQueue.put(runnable);
}
}
這里模擬的是固定數(shù)量的線程池
下面通過一個(gè)示例簡(jiǎn)單演示一下
public class Test {
public static void main(String[] args) throws InterruptedException {
MyThreadPoolExecutor myThreadPoolExecutor=new MyThreadPoolExecutor(5);
for (int i = 0; i < 100; i++) {
int count=i;
myThreadPoolExecutor.submit(()->{
System.out.println(Thread.currentThread().getName()+"執(zhí)行"+count);
});
}
}
}

到此這篇關(guān)于Java簡(jiǎn)單模擬實(shí)現(xiàn)一個(gè)線程池的文章就介紹到這了,更多相關(guān)Java 線程池內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
springboot application無法使用$獲取pom變量的問題及解決
這篇文章主要介紹了springboot application無法使用$獲取pom變量的問題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-02-02
Java兩種方法計(jì)算出階乘尾部連續(xù)0的個(gè)數(shù)
這篇文章主要介紹了Java兩種方法計(jì)算出階乘尾部連續(xù)0的個(gè)數(shù),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-03-03
基于SpringBoot實(shí)現(xiàn)圖片滑動(dòng)驗(yàn)證碼功能
本文詳細(xì)講解如何在Spring Boot項(xiàng)目中實(shí)現(xiàn)圖片滑動(dòng)驗(yàn)證碼功能,從原理闡述到完整代碼實(shí)現(xiàn),幫助開發(fā)者快速掌握這一實(shí)用的安全驗(yàn)證技術(shù),需要的朋友可以參考下2026-02-02
MyBatis使用Map與POJO類實(shí)現(xiàn)CRUD操作的步驟詳解
本文將通過實(shí)際案例,詳細(xì)講解在MyBatis中如何使用Map集合和POJO類兩種方式實(shí)現(xiàn)數(shù)據(jù)庫的增刪改查操作,解決常見映射問題,提高開發(fā)效率,需要的朋友可以參考下2025-12-12
詳解SpringBoot如何優(yōu)雅的進(jìn)行測(cè)試打包部署
這篇文章主要為大家詳細(xì)介紹了SpringBoot如何優(yōu)雅的進(jìn)行測(cè)試打包部署,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2024-12-12

