Java简单模拟实现一个线程池
作者: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 线程池内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
