废话不多说之间上代码
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);});}}
}