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 线程池内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
springboot application无法使用$获取pom变量的问题及解决
这篇文章主要介绍了springboot application无法使用$获取pom变量的问题及解决方案,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2022-02-02
MyBatis使用Map与POJO类实现CRUD操作的步骤详解
本文将通过实际案例,详细讲解在MyBatis中如何使用Map集合和POJO类两种方式实现数据库的增删改查操作,解决常见映射问题,提高开发效率,需要的朋友可以参考下2025-12-12


最新评论