线程池原理——生产者/消费者

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * 简化的线程池,仅用来说明工作原理.<br>
 * @author gongqiang <br>
 * @version 1.0.0 2021年6月9日<br>
 * @see 
 * @since JDK 1.5.0
 */
public class MyThreadPool {
	// 利用阻塞队列实现生产者 - 消费者模式
	private BlockingQueue<Runnable> workQueue;
	// 保存内部工作线程
	private List<WorkerThread> threads = new ArrayList<>();
	
	// 构造方法
	public MyThreadPool(int poolSize, BlockingQueue<Runnable> workQueue){
		this.workQueue = workQueue;
		// 创建工作线程
		for(int idx=0; idx<poolSize; idx++){
			WorkerThread work = new WorkerThread();
			work.start();
			threads.add(work);
		}
	}
	
	// 提交任务
	void execute(Runnable command){
		try {
			workQueue.put(command);
		} catch (InterruptedException e) {
			Thread.currentThread().interrupt();
		}
	}
	
	// 工作线程负责消费任务,并执行任务
	class WorkerThread extends Thread{
		public void run() {
			// 循环取任务并执行
			while(true){ 
				try {
					Runnable task = workQueue.take();
					task.run();
				} catch (InterruptedException e) {
					Thread.currentThread().interrupt();
				}
				
			}
		}
	}
	
	/**
	 * 示例.
	 * @param args
	 */
	public static void main(String[] args) {
		// 创建有界阻塞队列
		final BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>(2);
		// 创建线程池
		MyThreadPool pool = new MyThreadPool(10, workQueue);
		// 提交任务
		pool.execute(()->{
			System.out.println("hello");
		});
	}
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值