Java简单模拟实现一个线程池
更新时间:2024年01月26日 09:46:35 作者:djyyyg
本文主要介绍了Java简单模拟实现一个线程池,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
废话不多说之间上代码
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); } }
这里模拟的是固定数量的线程池
下面通过一个示例简单演示一下
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()+"执行"+count); }); } } }
到此这篇关于Java简单模拟实现一个线程池的文章就介绍到这了,更多相关Java 线程池内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
Java中实现String.padLeft和String.padRight的示例
本篇文章主要介绍了Java中实现String.padLeft和String.padRight,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧2017-09-09Spring Boot 基于注解的 Redis 缓存使用详解
本篇文章主要介绍了Spring Boot 基于注解的 Redis 缓存使用详解,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧2017-05-05浅谈Spring Cloud zuul http请求转发原理
这篇文章主要介绍了浅谈Spring Cloud zuul http请求转发原理,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧2018-08-08
最新评论