package com.wjl.demo.thread.mypool;
import java.lang.Thread.State;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;
/**
* 自定义线程池
*
* @author wangjl
*
*/
public class MyThreadPool {
// 仓库
private BlockingQueue<Runnable> queue;
// 工作线程
List<Worker> workers;
//可见性 工作状态
volatile boolean working = true;
public MyThreadPool(int poolSize, int queueSize) {
queue = new LinkedBlockingDeque<Runnable>(queueSize);
workers = new ArrayList<>(poolSize);
// 创建好线程
for (int i = 0; i < poolSize; i++) {
Worker w = new Worker(this);
workers.add(w);
w.start();
}
}
public void shutdown() {
// 让任务执行完成,然后关闭线程,不能接收新任务
this.working = false;
// 中断阻塞的线程
for (Thread worker : workers) {
State state = worker.getState();
if (state == Thread.State.BLOCKED || state == Thread.State.WAITING || state == Thread.State.TIMED_WAITING) {
System.out.println(worker.getName() +" 被中断");
worker.interrupt();// 中断线程
}
}
}
public boolean submit(Runnable task) {
if (working) {
return queue.offer(task);// 插入 返回一个特殊值 null或false
}
return false; // 不能接收任务
}
private static class Worker extends Thread {
MyThreadPool pool;
public Worker(MyThreadPool pool) {
this.pool = pool;
}
@Override
public void run() {
// super.run();
// 线程池工作 或者 有任务
while (pool.working || pool.queue.size() > 0) {
Runnable task = null;
try {
if (pool.working) {
task = pool.queue.take();// 从仓库取任务执行 没有会阻塞
} else {
task = pool.queue.poll();// 有就返回 ,没有就是null
}
} catch (InterruptedException e) {
e.printStackTrace();
}
if (task != null) {
task.run();
}
}
}
}
public static void main(String[] args) throws InterruptedException {
MyThreadPool pool = new MyThreadPool(3, 6);
for (int i = 0; i < 5; i++) {
pool.submit(() -> {
try {
Thread.sleep(200L);
} catch (InterruptedException e) {
// 中断异常
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "执行完任务");
});
}
Thread.sleep(220L);
pool.shutdown();
}
}
Java 自定义线程池
最新推荐文章于 2024-09-14 12:39:24 发布