Java簡單模擬實(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è)示例簡單演示一下
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簡單模擬實(shí)現(xiàn)一個(gè)線程池的文章就介紹到這了,更多相關(guān)Java 線程池內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Spring Web MVC框架學(xué)習(xí)之配置Spring Web MVC
這一篇文章講的是Spring Web MVC各部分的配置方法,包括Java代碼配置和XML文件配置以及MVC命名空間的使用方法。2017-03-03Fluent Mybatis實(shí)現(xiàn)環(huán)境隔離和租戶隔離
我們?cè)趯?shí)際的業(yè)務(wù)開發(fā)中,經(jīng)常會(huì)碰到環(huán)境邏輯隔離和租戶數(shù)據(jù)邏輯隔離的問題。本文就詳細(xì)的來介紹一下,感興趣的小伙伴們可以參考一下2021-08-08關(guān)于Java中XML Namespace 命名空間問題
這篇文章主要介紹了Java中XML Namespace 命名空間,XML命名空間是由國際化資源標(biāo)識(shí)符 (IRI) 標(biāo)識(shí)的 XML 元素和屬性集合,該集合通常稱作 XML“詞匯”,對(duì)XML Namespace 命名空間相關(guān)知識(shí)感興趣的朋友一起看看吧2021-08-08intellij idea創(chuàng)建第一個(gè)動(dòng)態(tài)web項(xiàng)目的步驟方法
這篇文章主要介紹了intellij idea創(chuàng)建第一個(gè)動(dòng)態(tài)web項(xiàng)目的步驟方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-10-10