线程池原理

动手实现线程池

package com.example.demo.threadpool;

public interface ThreadPool {

	/**
	 * 提交任务到线程池
	 * @param runnable 任务
	 */
	void execute(Runnable runnable);

	/**
	 * 关闭线程池
	 */
	void shutdown();

	/**
	 * 获取线程池的初始化大小
	 * @return 初始化大小
	 */
	int getInitSize();

	/**
	 * 获取线程池的最大线程数
	 * @return 最大线程数
	 */
	int getMaxSize();

	/**
	 * 获取线程池的核心线程数
	 * @return 线程数目
	 */
	int getCoreSize();

	/**
	 * 获取线程池中用于缓存任务队列的大小
	 * @return 队列大小
	 */
	int getQueueSize();

	/**
	 * 获取线程池中活跃线程的数量
	 * @return 线程数
	 */
	int getActiveCount();

	/**
	 * 查看线程池是否已经被shutdown
	 * @return {@code false} 未销毁
	 *         {@code true} 已销毁
	 */
	boolean isShutdown();
}

package com.example.demo.threadpool;

/**
 * 创建线程的工厂
 */
@FunctionalInterface
public interface ThreadFactory {
	/**
	 * 创建线程
	 * @param runnable run
	 * @return 线程
	 */
	Thread createThread(Runnable runnable);
}

package com.example.demo.threadpool;

/**
 * 任务队列,用于缓存已经提交到线程池中的任务
 */
public interface RunnableQueue {
	/**
	 * 当有新任务提交到线程池时先offer到队列中
	 * @param runnable 线程执行单元
	 */
	void offer(Runnable runnable);

	/**
	 * 工作线程通过 take方法获取 Runnable
	 * @return runnable
	 * @throws InterruptedException 中断异常
	 */
	Runnable take() throws InterruptedException;

	/**
	 * 队列中任务的数量
	 * @return 任务数
	 */
	int size();
}

package com.example.demo.threadpool;

/**
 * 拒绝策略
 */
@FunctionalInterface
public interface DenyPolicy {
	void reject(Runnable runnable, ThreadPool threadPool);

	/**
	 * 该拒绝策略会直接将任务丢弃
	 */
	class DiscardDenyPolicy implements DenyPolicy {

		@Override
		public void reject(Runnable runnable, ThreadPool threadPool) {
			//do nothing
		}
	}

	/**
	 * 该拒绝策略会向任务提交者抛出异常
	 */
	class AbortDenyPolicy implements DenyPolicy {

		@Override
		public void reject(Runnable runnable, ThreadPool threadPool) {
			throw new RunnableDenyException("The runnable " + runnable + " will be abort.");
		}
	}

	/**
	 * 该拒绝策略会使任务在提交者所在的线程中执行任务
	 */
	class RunnerDenyPolicy implements DenyPolicy {

		@Override
		public void reject(Runnable runnable, ThreadPool threadPool) {
			if (!threadPool.isShutdown()) {
				runnable.run();
			}
		}
	}
}

package com.example.demo.threadpool;

public class InternalTask implements Runnable {

	private final RunnableQueue runnableQueue;

	private volatile boolean running = true;

	public InternalTask(RunnableQueue runnableQueue) {
		this.runnableQueue = runnableQueue;
	}
	/**
	 * When an object implementing interface <code>Runnable</code> is used
	 * to create a thread, starting the thread causes the object's
	 * <code>run</code> method to be called in that separately executing
	 * thread.
	 * <p>
	 * The general contract of the method <code>run</code> is that it may
	 * take any action whatsoever.
	 *
	 * @see Thread#run()
	 */
	@Override
	public void run() {
		while (running && !Thread.currentThread().isInterrupted()) {
			try {
				Runnable task = runnableQueue.take();
				task.run();
			} catch (InterruptedException e) {
				running = false;
				break;
			}
		}
	}

	/**
	 * 停止当前任务,主要会在线程池的 shutdown方法中使用
	 */
	public void stop() {
		this.running = false;
	}
}

package com.example.demo.threadpool;

import java.util.LinkedList;

public class LinkedRunnableQueue implements RunnableQueue {

	private final int limit;

	private final DenyPolicy denyPolicy;

	private final LinkedList<Runnable> runnableList = new LinkedList<>();

	private final ThreadPool threadPool;


	public LinkedRunnableQueue(int limit, DenyPolicy denyPolicy, ThreadPool threadPool) {
		this.limit = limit;
		this.denyPolicy = denyPolicy;
		this.threadPool = threadPool;
	}

	/**
	 * 当有新任务提交到线程池时先offer到队列中
	 *
	 * @param runnable 线程执行单元
	 */
	@Override
	public void offer(Runnable runnable) {
		synchronized (this.runnableList) {
			if (this.runnableList.size() >= this.limit) {
				this.denyPolicy.reject(runnable, threadPool);
			} else {
				this.runnableList.addLast(runnable);
				runnableList.notifyAll();
			}
		}
	}

	/**
	 * 工作线程通过 take方法获取 Runnable
	 *
	 * @return runnable
	 * @throws InterruptedException 中断异常
	 */
	@Override
	public Runnable take() throws InterruptedException {
		synchronized (this.runnableList) {
			while (runnableList.isEmpty()) {
				try{
					runnableList.wait();
				} catch (InterruptedException e) {
					//
					throw e;
				}
			}
			return this.runnableList.removeFirst();
		}
	}

	/**
	 * 队列中任务的数量
	 *
	 * @return 任务数
	 */
	@Override
	public int size() {
		synchronized (this.runnableList) {
			return this.runnableList.size();
		}
	}
}

package com.example.demo.threadpool;

public class RunnableDenyException extends RuntimeException {

	public RunnableDenyException(String message) {
		super(message);
	}
}

package com.example.demo.threadpool;

import java.util.ArrayDeque;
import java.util.Queue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class BasicThreadPool extends Thread implements ThreadPool {

	private final int initSize;

	private final int maxSize;

	private final int coreSize;


	private int activeCount;

	private final ThreadFactory threadFactory;

	private final RunnableQueue runnableQueue;

	private volatile boolean isShutdown = false;

	private final Queue<ThreadTask> threadQueue = new ArrayDeque<>();

	private final static DenyPolicy DEFAULT_DENY_POLICY = new DenyPolicy.DiscardDenyPolicy();

	private final static ThreadFactory DEFAULT_THREAD_FACTORY = new DefaultThreadFactory();

	private final long keepAliveTime;

	private final TimeUnit timeUnit;

	public BasicThreadPool(int initSize, int maxSize, int coreSize, int queueSize) {
		this(initSize, maxSize, coreSize, DEFAULT_THREAD_FACTORY,
				queueSize, DEFAULT_DENY_POLICY, 10, TimeUnit.SECONDS);
	}

	public BasicThreadPool(int initSize, int maxSize, int coreSize, ThreadFactory threadFactory,
	                       int queueSize, DenyPolicy denyPolicy, long keepAliveTime, TimeUnit timeUnit) {
		this.initSize = initSize;
		this.maxSize = maxSize;
		this.coreSize = coreSize;
		this.threadFactory = threadFactory;
		this.runnableQueue = new LinkedRunnableQueue(queueSize, denyPolicy, this);
		this.keepAliveTime = keepAliveTime;
		this.timeUnit = timeUnit;
		this.init();
	}

	private void init() {
		start();
		for (int i = 0; i < initSize; i++) {
			newThread();
		}
	}

	private void newThread() {
		InternalTask internalTask = new InternalTask(runnableQueue);
		Thread thread = this.threadFactory.createThread(internalTask);
		ThreadTask threadTask = new ThreadTask(thread, internalTask);
		threadQueue.offer(threadTask);
		this.activeCount++;
		thread.start();
	}

	private void removeThread() {
		ThreadTask threadTask = threadQueue.remove();
		threadTask.internalTask.stop();
		this.activeCount--;
	}

	@Override
	public void run() {
		while (!this.isShutdown && !isInterrupted()) {
			try {
				this.timeUnit.sleep(this.keepAliveTime);
			} catch (InterruptedException e) {
				this.isShutdown = true;
				break;
			}
			synchronized (this) {
				if (this.isShutdown)
					break;
				if (this.runnableQueue.size() > 0 && this.activeCount < this.coreSize) {
					for (int i = this.initSize; i < this.coreSize; i++) {
						newThread();
					}
					continue;
				}

				if (this.runnableQueue.size() > 0 && this.activeCount < this.maxSize) {
					for (int i = this.coreSize; i < this.maxSize; i++) {
						newThread();
					}
				}

				if (runnableQueue.size() == 0 && this.activeCount > this.coreSize) {
					for (int i = this.coreSize; i < this.activeCount; i++) {
						removeThread();
					}
				}
			}
		}
	}

	/**
	 * 提交任务到线程池
	 *
	 * @param runnable 任务
	 */
	@Override
	public void execute(Runnable runnable) {
		if (this.isShutdown)
			throw new IllegalStateException("The thread pool is destroy");
		this.runnableQueue.offer(runnable);
	}

	/**
	 * 关闭线程池
	 */
	@Override
	public void shutdown() {
		synchronized (this) {
			if (this.isShutdown) return;
			this.isShutdown = true;
			this.threadQueue.forEach(threadTask -> {
				threadTask.internalTask.stop();
				threadTask.thread.interrupt();
			});
			this.interrupt();
		}
	}

	/**
	 * 获取线程池的初始化大小
	 *
	 * @return 初始化大小
	 */
	@Override
	public int getInitSize() {
		if (this.isShutdown)
			throw new IllegalStateException("The thread pool is destroy");
		return this.initSize;
	}

	/**
	 * 获取线程池的最大线程数
	 *
	 * @return 最大线程数
	 */
	@Override
	public int getMaxSize() {
		if (this.isShutdown)
			throw new IllegalStateException("The thread pool is destroy");
		return this.maxSize;
	}

	/**
	 * 获取线程池的核心线程数
	 *
	 * @return 线程数目
	 */
	@Override
	public int getCoreSize() {
		if (this.isShutdown)
			throw new IllegalStateException("The thread pool is destroy");
		return this.coreSize;
	}

	/**
	 * 获取线程池中用于缓存任务队列的大小
	 *
	 * @return 队列大小
	 */
	@Override
	public int getQueueSize() {
		if (this.isShutdown)
			throw new IllegalStateException("The thread pool is destroy");
		return this.runnableQueue.size();
	}

	/**
	 * 获取线程池中活跃线程的数量
	 *
	 * @return 线程数
	 */
	@Override
	public int getActiveCount() {
		synchronized (this) {
			return this.activeCount;
		}
	}

	/**
	 * 查看线程池是否已经被shutdown
	 *
	 * @return {@code false} 未销毁
	 * {@code true} 已销毁
	 */
	@Override
	public boolean isShutdown() {
		return this.isShutdown;
	}

	private static class ThreadTask {

		Thread thread;

		InternalTask internalTask;

		public ThreadTask(Thread thread, InternalTask internalTask) {
			this.thread = thread;
			this.internalTask = internalTask;
		}
	}

	private static class DefaultThreadFactory implements ThreadFactory {

		private static final AtomicInteger GROUP_COUNTER = new AtomicInteger(1);

		private static final ThreadGroup group = new ThreadGroup("MyThreadPool-" + GROUP_COUNTER.getAndIncrement());

		private static final AtomicInteger COUNTER = new AtomicInteger(0);

		public Thread createThread(Runnable runnable) {
			return new Thread(group, runnable, "thread-pool-" + COUNTER.getAndIncrement());
		}
	}
}

package com.example.demo.threadpool;

import java.util.concurrent.TimeUnit;

public class ThreadPoolDemo {
	public static void main(String[] args) throws InterruptedException{
		final ThreadPool threadPool = new BasicThreadPool(2, 6, 4, 1000);

		for (int i = 0; i < 20; i++) {
			threadPool.execute(() -> {
				try{
					TimeUnit.SECONDS.sleep(10);
					System.out.println(Thread.currentThread().getName() + " is running and done.");
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			});
		}

		for ( ; ; ) {
			System.out.println("active count: " + threadPool.getActiveCount());
			System.out.println("queue size: " + threadPool.getQueueSize());
			System.out.println("core size: " + threadPool.getCoreSize());
			System.out.println("max size: " + threadPool.getMaxSize());
			System.out.println("===================================================");

			TimeUnit.SECONDS.sleep(5);
		}
	}
}

//result
active count: 2
queue size: 18
core size: 4
max size: 6
===================================================
active count: 2
queue size: 18
core size: 4
max size: 6
===================================================
active count: 4
queue size: 16
core size: 4
max size: 6
===================================================
thread-pool-0 is running and done.
thread-pool-1 is running and done.
active count: 4
queue size: 14
core size: 4
max size: 6
===================================================
thread-pool-2 is running and done.
thread-pool-3 is running and done.
thread-pool-1 is running and done.
active count: 6
queue size: 9
core size: 4
max size: 6
thread-pool-0 is running and done.
===================================================
active count: 6
queue size: 8
core size: 4
max size: 6
===================================================
thread-pool-3 is running and done.
thread-pool-4 is running and done.
thread-pool-5 is running and done.
thread-pool-2 is running and done.
thread-pool-1 is running and done.
thread-pool-0 is running and done.
active count: 6
queue size: 2
core size: 4
max size: 6
===================================================
active count: 6
queue size: 2
core size: 4
max size: 6
===================================================
thread-pool-2 is running and done.
thread-pool-4 is running and done.
thread-pool-3 is running and done.
thread-pool-5 is running and done.
thread-pool-1 is running and done.
thread-pool-0 is running and done.
active count: 6
queue size: 0
core size: 4
max size: 6
===================================================
active count: 6
queue size: 0
core size: 4
max size: 6
===================================================
thread-pool-2 is running and done.
thread-pool-4 is running and done.
active count: 5
queue size: 0
core size: 4
max size: 6
===================================================
active count: 5
queue size: 0
core size: 4
max size: 6
===================================================
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值