阻塞队列(Blocking Queues)
- 当线程尝试从空队列获取元素时会被阻塞,直到其他线程插入元素。
- 当线程尝试向满队列添加元素时会被阻塞,直到其他线程取出元素。
public class BlockingQueue {
//用队列结构存储元素
private Queue<Object> queue = new LinkedList<>();
private int limit = 10;
public BlockingQueue(int limit) {
this.limit = limit;
}
public synchronized void enqueue(Object item) throws InterruptedException{
while(queue.size() >= limit){
wait();
}
//唤醒被空队列阻塞的线程
if(queue.size() == 0){
notifyAll();
}
queue.add(item);
}
public synchronized Object dequeue() throws InterruptedException{
while(queue.size() == 0){
wait();
}
//唤醒被满队列阻塞的线程
if(queue.size() >= limit){
notifyAll();
}
return queue.poll();
}
}
线程池(Thread Pools)
- 线程池开启固定数量的线程,来处理任务
- 把需要运行的任务放到阻塞队列中去
- 每当一条线程空闲,就从阻塞队列中取出一个任务并执行
//线程池类
public class ThreadPool {
//存放任务的阻塞队列
private BlockingQueue taskQueue = null;
//线程池
private List<PoolThread> threads = new ArrayList<PoolThread>();
//线程池停止标识
private boolean isStopped = false;
//初始化线程池
public ThreadPool(int noOfThreads, int maxNoOfTasks) {
this.taskQueue = new BlockingQueue(maxNoOfTasks);
for (int i = 0; i < noOfThreads; i++) {
threads.add(new PoolThread(taskQueue));
}
for (PoolThread thread : threads) {
thread.start();
}
}
//向阻塞队列插入新任务
public synchronized void execute(Runnable task) throws Exception {
if (this.isStopped)
throw new IllegalStateException("ThreadPool is stopped");
this.taskQueue.enqueue(task);
}
//停止线程池
public synchronized void stop() {
this.isStopped = true;
for (PoolThread thread : threads) {
thread.doStop();
}
}
}
//线程池中线程类
class PoolThread extends Thread {
//从此阻塞队列获取任务
private BlockingQueue taskQueue = null;
private boolean isStopped = false;
public PoolThread(BlockingQueue taskQueue) {
this.taskQueue = taskQueue;
}
public void run() {
while (!isStopped()) {
try {
Runnable runnable = (Runnable) taskQueue.dequeue();
runnable.run();
} catch (Exception e) {
// log or otherwise report exception,
// but keep pool thread alive.
}
}
}
public synchronized void doStop() {
isStopped = true;
this.interrupt(); // break pool thread out of dequeue() call.
}
public synchronized boolean isStopped() {
return isStopped;
}
}
参考 : Java Concurrency / Multithreading Tutorial
本文介绍了一种阻塞队列的实现方法,该队列在空或满时会阻塞线程,直至有可用资源。此外,还详细讲解了线程池的工作原理及其如何使用阻塞队列来分配和执行任务。
、线程池(Thread Pools)的原理与代码实现&spm=1001.2101.3001.5002&articleId=79052612&d=1&t=3&u=644e129a947f4513b20e9eb00e394799)
679

被折叠的 条评论
为什么被折叠?



