线程池的基本原理
声明任务队列、线程数量这两者数量主要由自己init,往队列中添加任务,如果超过数量则等待(阻塞),否则加入线程执行
import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingDeque; public class ThreadPoolDemo { //是否停止工作 //volatile保证线程访问此值的一致性 private volatile boolean isStop=false; //1.任务队列 private BlockingQueue<Runnable> blockingQueue; //2.线程 private List<Thread> workers; //3.执行线程 public class Worker extends Thread{ private ThreadPoolDemo threadPoolDemo=null; public Worker(ThreadPoolDemo poolDemo){ this.threadPoolDemo=poolDemo; } @Override public void run(){ //没有停止且队列内还有任务 while (!this.threadPoolDemo.isStop||this.threadPoolDemo.blockingQueue.size()>0){ Runnable task=null; try { if(!this.threadPoolDemo.isStop){ //阻塞获取 task=this.threadPoolDemo.blockingQueue.take(); }else{ //非阻塞获取(主要是将队列中的任务执行完毕) task=this.threadPoolDemo.blockingQueue.poll(); } } catch (InterruptedException e) { e.printStackTrace(); } if(task!=null) task.run(); } } } //初始化线程 public ThreadPoolDemo(int poolSize,int threadSize){ if(poolSize<=0||threadSize<=0){ throw new IllegalArgumentException("非法参数"); } this.blockingQueue= new LinkedBlockingDeque<>(poolSize); //线程安全 this.workers=Collections.synchronizedList(new ArrayList<Thread>()); for(int i=0;i<threadSize;i++){ Worker worker=new Worker(this); worker.start(); workers.add(worker); } } //将任务扔到队列中(阻塞) public void submit(Runnable task) throws InterruptedException { this.blockingQueue.put(task); } //关闭线程 public void shutDown(){ isStop=true; for(Thread thread:workers){ thread.interrupt();//中断 } } }
原文地址:https://www.cnblogs.com/jsyFoi/p/12519038.html
时间: 2024-10-11 16:05:52