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 线程池内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
Spring Web MVC框架学习之配置Spring Web MVC
这一篇文章讲的是Spring Web MVC各部分的配置方法,包括Java代码配置和XML文件配置以及MVC命名空间的使用方法。2017-03-03
intellij idea创建第一个动态web项目的步骤方法
这篇文章主要介绍了intellij idea创建第一个动态web项目的步骤方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2019-10-10


最新评论