|
| 1 | +package com.example.concurrency.threadPool; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.List; |
| 5 | +import java.util.concurrent.BlockingQueue; |
| 6 | +import java.util.concurrent.LinkedBlockingQueue; |
| 7 | + |
| 8 | +/** |
| 9 | + * 描述: |
| 10 | + * 简化的线程池,仅用来说明工作原理 |
| 11 | + * |
| 12 | + * @author zed |
| 13 | + * @since 2019-06-18 3:10 PM |
| 14 | + */ |
| 15 | + |
| 16 | +public class MyThreadPool{ |
| 17 | + /** |
| 18 | + * 利用阻塞队列实现生产者 - 消费者模式 |
| 19 | + */ |
| 20 | + private BlockingQueue<Runnable> workQueue; |
| 21 | + /** |
| 22 | + * 保存内部工作线程 |
| 23 | + */ |
| 24 | + private List<WorkerThread> threads = new ArrayList<>(); |
| 25 | + // 构造方法 |
| 26 | + public MyThreadPool(int poolSize, BlockingQueue<Runnable> workQueue){ |
| 27 | + this.workQueue = workQueue; |
| 28 | + // 创建工作线程 |
| 29 | + for(int idx=0; idx<poolSize; idx++){ |
| 30 | + WorkerThread work = new WorkerThread(); |
| 31 | + work.start(); |
| 32 | + threads.add(work); |
| 33 | + } |
| 34 | + } |
| 35 | + |
| 36 | + /** |
| 37 | + * 提交任务 |
| 38 | + * @param command command |
| 39 | + */ |
| 40 | + public void execute(Runnable command){ |
| 41 | + try{ |
| 42 | + workQueue.put(command); |
| 43 | + |
| 44 | + }catch (InterruptedException e){ |
| 45 | + Thread.currentThread().interrupt(); |
| 46 | + |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + /** |
| 51 | + * 工作线程负责消费任务,并执行任务 |
| 52 | + */ |
| 53 | + class WorkerThread extends Thread{ |
| 54 | + @Override |
| 55 | + public void run() { |
| 56 | + // 循环取任务并执行 |
| 57 | + while(true){ |
| 58 | + try{ |
| 59 | + Runnable task = workQueue.take(); |
| 60 | + task.run(); |
| 61 | + }catch (InterruptedException e){ |
| 62 | + Thread.currentThread().interrupt(); |
| 63 | + } |
| 64 | + |
| 65 | + } |
| 66 | + } |
| 67 | + } |
| 68 | + |
| 69 | + public static void main(String[] args) { |
| 70 | + // 创建有界阻塞队列 |
| 71 | + BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>(2); |
| 72 | + // 创建线程池 |
| 73 | + MyThreadPool pool = new MyThreadPool(10, workQueue); |
| 74 | + // 提交任务 |
| 75 | + pool.execute(()->{ |
| 76 | + System.out.println("hello"); |
| 77 | + }); |
| 78 | + |
| 79 | + |
| 80 | + } |
| 81 | + |
| 82 | +} |
| 83 | + |
| 84 | + |
0 commit comments