理解线程池原理
1、理解什么是线程
线程是程序运行的最小单位
2、Thread、Runnable、Callable有什么联系
Thread是线程,Runnable和Callable可以理解为任务,线程的作用是把任务运送到cpu去执行。
public class threadDemo implements Runnable{ @Override public void run(){ //线程工作内容 } }
public class threadDemo implements Callable{ @Override public String run(){ //线程内容 return "hh"; } }
3、 实现一个简易线程池

public class FixThreadPool { private List<Thread> workers;//线程列表 private LinkedBlockingQueue<Runnable> blockingQueue;//任务队列 //线程 public static class worker extends Thread{ private FixThreadPool pool; public worker(FixThreadPool pool) { this.pool = pool; } @Override public void run() { while (true) { //反复执行 Runnable task = null; try { //从任务队列中取出任务 task = this.pool.blockingQueue.take(); } catch (InterruptedException e) { e.printStackTrace(); } //执行任务 if (null != task) { task.run(); } } } } public FixThreadPool(int poolSize, int taskSize) { if(poolSize <= 0 || taskSize <= 0){ throw new IllegalArgumentException("非法参数"); } // this.FixThreadPool = new ArrayList<>(poolSize); this.blockingQueue = new LinkedBlockingQueue(taskSize); this.workers = Collections.synchronizedList(new ArrayList<>()); for (int i = 0; i < poolSize; i++) { worker worker = new worker(this); workers.add(worker); worker.start(); } } public boolean submit(Runnable task) { return this.blockingQueue.offer(task); } }

浙公网安备 33010602011771号