在网络课程中学习了简单线程池,为加深记忆,照抄一遍
BlockingQueue队列
/**
* BlockingQueue 特点
* 抛出异常 特殊值 阻塞 超时
* 1、添加 add(e) offer(e) put(e) offer(e, time, util)
* 2、删除 remove() poll() take() poll(time, util)
* 3、检查 element() peek() 不可用 不可用
*/
public class FixedThreadPool {
//任务仓库
private BlockingQueue<Runnable> queue;
//工作线程
List<Worker> workers;
//线程池状态
private volatile boolean working = true;
public FixedThreadPool(int threadCount, int taskCount){
queue = new LinkedBlockingQueue<Runnable>(taskCount);
workers = new Vector<>();
for (int i = 0; i < threadCount; i++) {
Worker worker = new Worker(this);
worker.start();
System.out.println(worker.getName()+"==========初始话工作线程");
workers.add(worker);
}
}
/**
* @Description提交任务
* @param runnable
* @return
*/
public boolean submit(Runnable runnable) {
if(working) {//判断是否关闭 关闭后不能提交任务
return queue.offer(runnable);
}
return false;
}
/**
* @Description 关闭线程池(让线程池中任务结束后才关闭)
* @param runnable
* @return
*/
public void shutDown() {
this.working = false;//设置线程池状态
for(Worker worker : workers) {//中断已阻塞的线程
if (worker.getState().equals(State.BLOCKED) || worker.getState().equals(State.TERMINATED)
|| worker.getState().equals(State.TIMED_WAITING)
|| worker.getState().equals(State.WAITING)) {
worker.interrupt();
}
}
}
/**
* @Description 工作线程
* @author Jesse
*
*/
private static class Worker extends Thread{
private FixedThreadPool pool;
public Worker(FixedThreadPool pool) {
super();
this.pool = pool;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"==========线程开始执行任务");
int count = 0;
Runnable task;
while (pool.working || pool.queue.size() > 0) {
try {
if(pool.working) {
task = pool.queue.take();
} else {
task = pool.queue.poll();
}
if(task != null) {
task.run();
}
System.out.println(Thread.currentThread().getName()+"============执行第"+(++count)+"个任务");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+"==========线程执行结束");
}
}
}