Java 自定义线程池

package com.wjl.demo.thread.mypool;

import java.lang.Thread.State;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;

/**
 * 自定义线程池
 * 
 * @author wangjl
 *
 */
public class MyThreadPool {
	// 仓库
	private BlockingQueue<Runnable> queue;
	// 工作线程
	List<Worker> workers;
	//可见性 工作状态
	volatile boolean working = true;

	public MyThreadPool(int poolSize, int queueSize) {
		queue = new LinkedBlockingDeque<Runnable>(queueSize);
		workers = new ArrayList<>(poolSize);
		// 创建好线程
		for (int i = 0; i < poolSize; i++) {
			Worker w = new Worker(this);
			workers.add(w);
			w.start();
		}
	}

	public void shutdown() {
		// 让任务执行完成,然后关闭线程,不能接收新任务
		this.working = false;

		// 中断阻塞的线程
		for (Thread worker : workers) {
			State state = worker.getState();
			if (state == Thread.State.BLOCKED || state == Thread.State.WAITING || state == Thread.State.TIMED_WAITING) {
				System.out.println(worker.getName() +" 被中断");
				worker.interrupt();// 中断线程
			}
		}
	}

	public boolean submit(Runnable task) {
		if (working) {
			return queue.offer(task);// 插入 返回一个特殊值 null或false
		}
		return false; // 不能接收任务
	}

	private static class Worker extends Thread {
		MyThreadPool pool;

		public Worker(MyThreadPool pool) {
			this.pool = pool;
		}

		@Override
		public void run() {
//			super.run();
			// 线程池工作 或者 有任务
			while (pool.working || pool.queue.size() > 0) {
				Runnable task = null;
				try {
					if (pool.working) {
						task = pool.queue.take();// 从仓库取任务执行 没有会阻塞
					} else {
						task = pool.queue.poll();// 有就返回 ,没有就是null
					}

				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				if (task != null) {
					task.run();
				}
			}
		}
	}

	public static void main(String[] args) throws InterruptedException {
		MyThreadPool pool = new MyThreadPool(3, 6);
		for (int i = 0; i < 5; i++) {
			pool.submit(() -> {
				try {
					Thread.sleep(200L);
				} catch (InterruptedException e) {
					// 中断异常
					e.printStackTrace();
				}
				System.out.println(Thread.currentThread().getName() + "执行完任务");
			});
		}
		Thread.sleep(220L);
		pool.shutdown();
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值