Java并发编程:阻塞队列(Blocking Queues)、线程池(Thread Pools)的原理与代码实现

阻塞队列(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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值