// 假设Java线程池采用一般意义上池化资源的设计方法
class ThreadPool {
// 获取空闲线程
Thread acquire() {
}
// 释放线程
void release(Thread t) {
}
}
// 期望的使用
ThreadPool pool;
Thread T1 = pool.acquire();
// 传入Runnable对象
T1.execute(() -> {
// 具体业务逻辑
});
业界线程池的设计,普遍采用 生产者-消费者模式 ,线程池的使用方是生产者,线程池本身是消费者
public class MyThreadPool {
// 工作线程负责消费任务并执行任务
class WorkerThread extends Thread {
@Override
public void run() {
// 循环取任务并执行
while (true) {
Runnable task = null;
try {
task = workQueue.take();
} catch (InterruptedException e) {
}
task.run();
}
}
}
// 利用阻塞队列实现生产者-消费者模式
private BlockingQueue<Runnable> workQueue;
// 内部保存工作线程
List<WorkerThread> threads = new ArrayList<>();
public MyThreadPool(int poolSize, BlockingQueue<Runnable> workQueue) {
this.workQueue = workQueue;
for (int i = 0; i < poolSize; i++) {
WorkerThread work = new WorkerThread();
work.start();
threads.add(work);
}
}
// 提交任务
public void execute(Runnable command) throws InterruptedException {
workQueue.put(command);
}
public static void main(String[] args) throws InterruptedException {
// 创建有界阻塞队列
BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>(2);
// 创建线程池
MyThreadPool pool = new MyThreadPool(10, workQueue);
// 提交任务
pool.execute(() -> {
System.out.println("hello");
});
}
}
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler)
// 让所有线程都支持超时,如果线程池很闲,那么将撤销所有线程
public void allowCoreThreadTimeOut(boolean value)
try {
// 业务逻辑
} catch (RuntimeException x) {
// 按需处理
} catch (Throwable x) {
// 按需处理
}
转载请注明出处:http://zhongmingmao.me/2019/05/14/java-concurrent-thread-pool/
访问原文「Java并发 -- 线程池」获取最佳阅读体验并参与讨论