6. ThreadGroup详解
6.1 ThreadGroup和Thread
新的线程都会被加入到main线程所在的group中, main线程的group名字同线程名。ThreadGroup同样存在父子关系. 如下:
6.2 创建ThreadGroup
package com.zoro.concurrent.chapter06;
/**
* 创建ThreadGroup
*
* @author yx.jiang
* @date 2021/7/27 10:26
*/
public class ThreadGroupCreator {
public static void main(String[] args) {
ThreadGroup currentGroup = Thread.currentThread().getThreadGroup();
//currentGroup = java.lang.ThreadGroup[name=main,maxpri=10]
System.out.println("currentGroup = " + currentGroup);
ThreadGroup group1 = new ThreadGroup("Group1");
//输出true
System.out.println(group1.getParent() == currentGroup);
ThreadGroup group2 = new ThreadGroup(group1, "Group2");
//输出true
System.out.println(group2.getParent() == group1);
}
}
6.3 复制Thread数组和ThreadGroup数组
6.3.1 复制Thread数组
前两个方法会将ThreadGroup中的active线程全部复制到Thread数组中
recurse = true; 递归复制——将所有子group中的active线程都递归到Thread数组中
recurse = false; 非递归复制
- enumerate获取的仅仅是个预估值, 并不能100%地保证当前group的活跃线程.如: 在调用复制之后, 某个线程结束了生命周期/新的线程加入了进来, 均会导致数据的不准确
enumerate方法的返回值int较Thread[]的长度更为真实, 如: 定义了数组长度的Thread数组, 那么enumerate仅仅会将当前活跃的thread分别放进数组中, 而int代表真是的数量, 而并非数组的长度;
6.3.2 复制ThreadGroup数组
6.4 ThreadGroup操作
ThreadGroup不能提供对线程的管理, 主要功能是对线程 进行组织.
6.4.1 ThreadGroup基操
6.4.2 ThreadGroup的interrupt
interrupt一个ThreadGroup会导致该group中所有的active线程都被interrupt, 即: 该group中每个线程的interrupt标识都被设置了
6.4.3 ThreadGroup的destroy
destroy用于销毁ThreadGroup, 只针对一个没有任何active线程的group进行一次destroy标记, 调用该方法的直接结果是在父group中将自己移除
6.4.4 守护ThreadGroup
像Thread一样, 但是将ThreadGroup设置为daemon, 并不会影响线程的daemon属性; 如果一个ThreadGroup的daemon被设置为true, 那么在group中没有任何active线程的时候该group将自动destroy
7. Hook线程以及捕获线程异常执行
7.1 获取线程运行时异常
_public static void _setDefaultUncaughtExceptionHandler(Thread.UncaughtExceptionHandler eh)
- _public static _Thread.UncaughtExceptionHandler getDefaultUncaughtExceptionHandler()
- _public _Thread.UncaughtExceptionHandler getUncaughtExceptionHandler()
- _public void _setUncaughtExceptionHandler(Thread.UncaughtExceptionHandler eh)
7.1.1 UncaughtExceptionHandler介绍
线程在执行单元中是不允许抛出checked异常的, 且线程运行在自己的上下文中, 派生它的线程将无法直接获得它运行中出现的异常信息; UncaughtExceptionHandler 接口: 当线程在运行过程中出现异常时, 会回调UncaughtExceptionHandler 接口, 从而得知是哪个线程在运行时出错, 以及出现了什么样的错误
java.lang.Thread#dispatchUncaughtException()调用了java.lang.Thread.UncaughtExceptionHandler#uncaughtException()
实际运行过程中出现异常, JVM会调用dispatchUncaughtException()方法, 该方法会将对应的线程实例以及异常信息传递给回调接口.
@FunctionalInterface
public interface UncaughtExceptionHandler {
/**
* Method invoked when the given thread terminates due to the
* given uncaught exception.
* <p>Any exception thrown by this method will be ignored by the
* Java Virtual Machine.
* @param t the thread
* @param e the exception
*/
void uncaughtException(Thread t, Throwable e);
}
/**
* Dispatch an uncaught exception to the handler. This method is
* intended to be called only by the JVM.
*/
private void dispatchUncaughtException(Throwable e) {
getUncaughtExceptionHandler().uncaughtException(this, e);
}
7.1.2 实例
package com.zoro.concurrent.chapter07;
import java.util.concurrent.TimeUnit;
/**
* 捕获线程异常
*
* @author yx.jiang
* @date 2021/7/27 10:26
*/
public class CaptureThreadException {
/**
* 输出如下:
* Test-Threadoccur exception:
* java.lang.ArithmeticException: / by zero
* at com.zoro.concurrent.chapter07.CaptureThreadException.lambda$main$1(CaptureThreadException.java:27)
* at java.lang.Thread.run(Thread.java:748)
*/
public static void main(String[] args) {
//设置回调接口
Thread.setDefaultUncaughtExceptionHandler((t, e) -> {
System.out.println(t.getName() + "occur exception: ");
e.printStackTrace();
});
final Thread thread = new Thread(() -> {
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
//e.printStackTrace();
}
//unchecked异常
System.out.println(1 / 0);
}, "Test-Thread");
thread.start();
}
}
7.1.3 分析sourceCode
java.lang.Thread#getUncaughtExceptionHandler
public UncaughtExceptionHandler getUncaughtExceptionHandler() {
return uncaughtExceptionHandler != null ?
uncaughtExceptionHandler : group;
}
java.lang.ThreadGroup#uncaughtException
public void uncaughtException(Thread t, Throwable e) {
if (parent != null) {
parent.uncaughtException(t, e);
} else {
Thread.UncaughtExceptionHandler ueh =
Thread.getDefaultUncaughtExceptionHandler();
if (ueh != null) {
ueh.uncaughtException(t, e);
} else if (!(e instanceof ThreadDeath)) {
System.err.print("Exception in thread \""
+ t.getName() + "\" ");
e.printStackTrace(System.err);
}
}
}
- 该ThreadGroup如果有父ThreadGroup, 则直接调用父ThreadGroup的uncaughtException方法
- 如果设置了全局默认的UncaughtExceptionHandler, 则调用uncaughtException方法
- 若既没有父ThreadGroup, 又没有设置全局默认的UncaughtExceptionHandler, 则会直接将异常的堆栈信息定向到System.err中 ```java package com.zoro.concurrent.chapter07;
import java.util.concurrent.TimeUnit;
/**
- @author yx.jiang
- @date 2021/7/27 10:26 */ public class EmptyExceptionHandler {
/**
* 输出如下:
* mainGroup.getName() = main
* mainGroup.getParent() = java.lang.ThreadGroup[name=system,maxpri=10]
* mainGroup.getParent().getParent() = null
* Exception in thread "Test-Thread" java.lang.ArithmeticException: / by zero
* at com.zoro.concurrent.chapter07.EmptyExceptionHandler.lambda$main$0(EmptyExceptionHandler.java:29)
* at java.lang.Thread.run(Thread.java:748)
*/
public static void main(String[] args) {
//设置回调接口
ThreadGroup mainGroup = Thread.currentThread().getThreadGroup();
System.out.println("mainGroup.getName() = " + mainGroup.getName());
System.out.println("mainGroup.getParent() = " + mainGroup.getParent());
System.out.println("mainGroup.getParent().getParent() = " + mainGroup.getParent().getParent());
final Thread thread = new Thread(() -> {
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
//e.printStackTrace();
}
//unchecked异常
System.out.println(1 / 0);
}, "Test-Thread");
thread.start();
}
}
![](https://cdn.nlark.com/yuque/0/2021/jpeg/708204/1627541129891-79306ddd-43b2-4353-8ce9-efc5828d0948.jpeg)
<a name="ac0bT"></a>
### 7.2 注入钩子线程
<a name="t3szI"></a>
#### 7.2.1 Hook线程介绍
```java
package com.zoro.concurrent.chapter07;
import java.util.concurrent.TimeUnit;
/**
* 钩子线程
*
* @author yx.jiang
* @date 2021/7/27 10:26
*/
public class ThreadHook {
/**
* 输出如下:
* 程序即将关闭...
* 钩子线程1启动...
* 钩子线程2启动...
* 钩子线程1即将关闭
* 钩子线程2即将关闭
*/
public static void main(String[] args) {
//注册第一个钩子线程
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
System.out.println("钩子线程1启动...");
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("钩子线程1即将关闭");
}));
//注册第二个钩子线程
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
System.out.println("钩子线程2启动...");
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("钩子线程2即将关闭");
}));
System.out.println("程序即将关闭...");
}
}
7.2.2 Hook实战
package com.zoro.concurrent.chapter07;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* 防止重复
* <h>防止某个程序重复启动, 在进程启动时创建一个.lock文件, 进程收到中断信号的时候会删除这个lock文件</h>
*
* @author yx.jiang
* @date 2021/7/27 10:26
*/
public class PreventDuplicated {
private static final String LOCK_PATH = "D:\\idea tool box\\locks";
private static final String LOCK_FILE = ".lock";
private static final String PERMISSION = "rw-------";
public static void main(String[] args) throws IOException {
//注入Hook线程, 在程序退出时删除lock文件
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
System.out.println("程序接收到 kill 信号.");
getLockFile().toFile().delete();
}));
//检查是否存在.lock文件
checkRunning();
//简单模拟当前进程正在运行
for (; ; ) {
try {
TimeUnit.SECONDS.sleep(1);
System.out.println("程序正在运行...");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void checkRunning() throws IOException {
Path path = getLockFile();
if (path.toFile().exists()) {
throw new RuntimeException("程序正在运行...");
}
//WINDOWS
Path file1 = Files.createFile(path);
File file = file1.toFile();
file.setReadable(true);
file.setWritable(true);
System.out.println(file.exists() + " " + file.getAbsolutePath());
// 'posix:permissions' not supported as initial attribute
// UNIX
// Set<PosixFilePermission> perms = PosixFilePermissions.fromString(PERMISSION);
// Files.createFile(path, perms);
}
public static Path getLockFile() {
return Paths.get(LOCK_PATH, LOCK_FILE);
}
}
7.2.3 注意事项
- Hook线程只有在收到退出信号的时候会被执行, 如果在kill的时候使用了参数
**-9**
, 那么Hook线程不会得到执行, 进程将会立即退出, 因此.lock文件将得不到清理. - Hook线程中也可以执行一些资源的释放工作, 比如关闭文件句柄, socket链接, 数据库connection等.
尽量不要在Hook线程中执行一些耗时非常长的操作, 因为会导致程序迟迟不能退出
8. 线程池原理及自定义线程池
8.1 线程池原理
任务队列: 用于缓存提交任务
- 线程数量管理功能: 一个线程池必须能够很好的管理和控制线程数量, 可通过如下三个参数来实现, 比如创建线程池时初始的线程数量init; 线程池自动扩充时最大的核心线程数量max; 在线程池空闲时需要释放线程但是也要维护一定数量的活跃数量或者核心数量core. init <= core <= max;
- 任务拒绝策略: 如果线程数量已经到上限且任务队列已满, 则需要有相应的拒绝策略来通知任务提交者;
- 线程工厂: 主要用于个性化定制线程, 比如将线程设置为守护线程以及设置线程名称等;
- QueueSize: 任务队列主要用于存放提交的Runnable, 但是为了防止内存溢出, 需要有limit数量对其进行控制
- keepedAlive时间: 该时间主要决定线程各个重要参数自动维护的时间间隔.
8.2 线程池实现
ThreadPool
```java package com.zoro.concurrent.chapter08.threadpool;
/**
- 线程池接口 *
- @author yx.jiang
@date 2021/7/27 10:26 / public interface ThreadPool { /*
- 提交任务到线程池 *
@param runnable runnable */ void execute(Runnable runnable);
/**
关闭并销毁线程池 */ void shutdown();
/**
- 获取线程池的初始化大小 *
@return */ int getInitSize();
/**
- 获取线程池最大的线程数 *
@return */ int getMaxSize();
/**
- 获取线程池的核心线程数量 *
@return */ int getCoreSize();
/**
- 获取线程池中用于缓存任务队列的大小 *
@return */ int getQueueSize();
/**
- 获取线程池中活跃线程的数量 *
@return */ int getActiveCount();
/**
- 查看线程池是否已经被销毁(shutdown) *
- @return */ boolean isShutdown(); }
<a name="KWWWf"></a>
#### ThreadFactory
```java
package com.zoro.concurrent.chapter08.threadpool;
/**
* 创建Thread的工厂
*
* @author yx.jiang
* @date 2021/7/27 10:26
*/
@FunctionalInterface
public interface ThreadFactory {
/**
* 创建线程
*
* @param runnable 执行单元/任务
* @return 线程
*/
Thread createThread(Runnable runnable);
}
RunnableQueue
package com.zoro.concurrent.chapter08.threadpool;
/**
* 任务队列
*
* @author yx.jiang
* @date 2021/7/27 10:26
*/
public interface RunnableQueue {
/**
* 将任务提交至队列中
*
* @param runnable
*/
void offer(Runnable runnable);
/**
* 工作线程通过take获取Runnable
*/
Runnable take() throws InterruptedException;
/**
* 获取任务队列中任务的数量
*
* @return
*/
int size();
}
DenyPolicy
package com.zoro.concurrent.chapter08.threadpool;
/**
* 拒绝策略
*
* @author yx.jiang
* @date 2021/7/27 10:26
*/
@FunctionalInterface
public interface DenyPolicy {
/**
* 拒绝方法
*
* @param runnable 任务/执行单元
* @param threadPool 线程池
*/
void reject(Runnable runnable, ThreadPool threadPool);
/**
* 直接丢弃Runnable任务
*/
class DiscardDenyPolicy implements DenyPolicy {
@Override
public void reject(Runnable runnable, ThreadPool threadPool) {
//do nothing
}
}
/**
* 抛出{@link RunnableDenyException}异常
*/
class AbortDenyPolicy implements DenyPolicy {
@Override
public void reject(Runnable runnable, ThreadPool threadPool) {
throw new RunnableDenyException("执行单元/任务: " + runnable + "将被放弃");
}
}
/**
* 交由调用者的线程直接运行Runnable, 而不会被加入到线程池中
*/
class RunnerDenyPolicy implements DenyPolicy {
@Override
public void reject(Runnable runnable, ThreadPool threadPool) {
//do nothing
}
}
}
RunnableDenyException
package com.zoro.concurrent.chapter08.threadpool;
/**
* 可运行拒绝异常
*
* @author yx.jiang
* @date 2021/7/27 10:26
*/
public class RunnableDenyException extends RuntimeException {
public RunnableDenyException(String message) {
super(message);
}
}
LinkedRunnableQueue
package com.zoro.concurrent.chapter08.threadpool;
import java.util.LinkedList;
/**
* 任务队列实现
*
* @author yx.jiang
* @date 2021/7/27 10:26
*/
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;
}
@Override
public void offer(Runnable runnable) {
synchronized (runnableList) {
if (runnableList.size() >= limit) {
//无法容纳新的任务时执行拒绝策略
denyPolicy.reject(runnable, threadPool);
} else {
//将任务加入到队尾, 并唤醒阻塞中的线程
runnableList.addLast(runnable);
runnableList.notifyAll();
}
}
}
@Override
public Runnable take() throws InterruptedException {
synchronized (runnableList) {
while (runnableList.isEmpty()) {
try {
//如果任务队列中没有可执行的任务,则当前线程会挂起,进入runnableList关联的monitor waitSet 中等待唤醒(新的任务加入)
runnableList.wait();
} catch (InterruptedException e) {
throw e;
}
}
//从任务队列头部移除一个任务
return runnableList.removeFirst();
}
}
@Override
public int size() {
synchronized (runnableList) {
//返回当前任务队列中的任务数
return runnableList.size();
}
}
}
InternalTask
package com.zoro.concurrent.chapter08.threadpool;
/**
* 内部任务(线程池内)
*
* @author yx.jiang
* @date 2021/7/27 10:26
*/
public class InternalTask implements Runnable {
private final RunnableQueue runnableQueue;
private volatile boolean running = true;
public InternalTask(RunnableQueue runnableQueue) {
this.runnableQueue = runnableQueue;
}
@Override
public void run() {
//如果当任务为running并且没有被中断, 则其将不断的从queue中获取runnable, 然后执行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;
}
}
BasicThreadPool
package com.zoro.concurrent.chapter08.threadpool;
import java.util.ArrayDeque;
import java.util.Queue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
* 初始化线程池
* FIXME: 这里不建议 extends Thread; 用组合的方式更好些;
*
* @author yx.jiang
* @date 2021/7/27 10:26
*/
public class BasicThreadPool extends Thread implements ThreadPool {
public static final String THREAD_POOL_DESTROYED = "线程池已销毁";
/**
* 初始化线程数量
*/
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 static final DenyPolicy DEFAULT_DENY_POLICY = new DenyPolicy.DiscardDenyPolicy();
/**
* 默认线程工厂
*/
private static final ThreadFactory DEFAULT_THREAD_FACTORY = new DefaultThreadFactory();
private final long keepAliveTime;
private final TimeUnit timeUnit;
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();
}
public BasicThreadPool(int initSize, int maxSize, int coreSize, int queueSize) {
this(initSize, maxSize, coreSize, DEFAULT_THREAD_FACTORY, queueSize, DEFAULT_DENY_POLICY, 10, TimeUnit.SECONDS);
}
/**
* 初始化时 —— 创建initSize个线程
*/
private void init() {
start();
for (int i = 0; i < initSize; i++) {
newThread();
}
}
private void newThread() {
//创建线程并启动
InternalTask internalTask = new InternalTask(runnableQueue);
Thread thread = threadFactory.createThread(internalTask);
ThreadTask threadTask = new ThreadTask(thread, internalTask);
threadQueue.add(threadTask);
this.activeCount++;
thread.start();
}
private void removeThread() {
//从线程池中移除某个线程
ThreadTask threadTask = threadQueue.remove();
threadTask.internalTask.stop();
this.activeCount--;
}
/**
* 同步代码块:为了阻止在线程维护过程中线程池销毁引起的数据不一致问题
*/
@Override
public void run() {
//该方法继承自Thread,主要用于维护线程数量,如:扩容、回收工作
while (!isShutdown && !isInterrupted()) {
try {
timeUnit.sleep(keepAliveTime);
} catch (InterruptedException e) {
isShutdown = true;
break;
}
synchronized (this) {
if (isShutdown) {
break;
}
//当前的队列中有任务尚未处理,且activeCount < coreSize,继续扩容
if (runnableQueue.size() > 0 && activeCount < coreSize) {
for (int i = initSize; i < coreSize; i++) {
newThread();
}
//目的:不想让线程的扩容直接到达maxSize
continue;
}
//当前的对列中有任务尚未处理,且activeCount < maxSize,继续扩容
if (runnableQueue.size() > 0 && activeCount < maxSize) {
for (int i = coreSize; i < maxSize; i++) {
newThread();
}
}
//若任务队列无任务,需要回收,回收至coreSize即可
if (runnableQueue.size() == 0 && activeCount > coreSize) {
for (int i = coreSize; i < activeCount; i++) {
removeThread();
}
}
}
}
}
@Override
public void execute(Runnable runnable) {
if (this.isShutdown) {
throw new IllegalStateException(THREAD_POOL_DESTROYED);
}
//向任务队列插入Runnable
this.runnableQueue.offer(runnable);
}
/**
* 同步机制保护:防止与线程池本身的维护线程引起数据冲突
* 停止BasicThreadPool线程,停止线程池中的活动线程,将isShutdown开关改为true
*/
@Override
public void shutdown() {
synchronized (this) {
if (isShutdown) {
return;
}
isShutdown = true;
threadQueue.forEach(threadTask -> {
threadTask.internalTask.stop();
threadTask.thread.interrupt();
});
this.interrupt();
}
}
@Override
public int getInitSize() {
if (isShutdown) {
throw new IllegalStateException("线程池已销毁");
}
return this.initSize;
}
@Override
public int getMaxSize() {
if (isShutdown) {
throw new IllegalStateException("线程池已销毁");
}
return this.maxSize;
}
@Override
public int getCoreSize() {
if (isShutdown) {
throw new IllegalStateException("线程池已销毁");
}
return this.coreSize;
}
@Override
public int getQueueSize() {
if (isShutdown) {
throw new IllegalStateException("线程池已销毁");
}
return runnableQueue.size();
}
@Override
public int getActiveCount() {
synchronized (this) {
return this.activeCount;
}
}
@Override
public boolean isShutdown() {
return this.isShutdown;
}
/**
* {@link Thread} 和 {@link InternalTask}的一个组合
*/
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);
@Override
public Thread createThread(Runnable runnable) {
return new Thread(group, runnable, "thread-pool-" + COUNTER.getAndIncrement());
}
}
}
ThreadPoolTest
package com.zoro.concurrent.chapter08;
import com.zoro.concurrent.chapter08.threadpool.BasicThreadPool;
import java.util.concurrent.TimeUnit;
/**
* 线程池测试类
*
* @author yx.jiang
* @date 2021/7/27 10:26
*/
public class ThreadPoolTest {
public static void main(String[] args) throws InterruptedException {
BasicThreadPool basicThreadPool = new BasicThreadPool(2, 6, 4, 1000);
for (int i = 0; i < 20; i++) {
basicThreadPool.execute(() -> {
try {
TimeUnit.SECONDS.sleep(10);
System.out.println(Thread.currentThread().getName() + " 已启动");
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
//验证线程池中的动态扩展情况及任务执行情况;最终activeCount = coreSize
/*for (; ;) {
System.out.println("basicThreadPool.getActiveCount() = " + basicThreadPool.getActiveCount());
System.out.println("basicThreadPool.getQueueSize() = " + basicThreadPool.getQueueSize());
System.out.println("basicThreadPool.getCoreSize() = " + basicThreadPool.getCoreSize());
System.out.println("basicThreadPool.getMaxSize() = " + basicThreadPool.getMaxSize());
System.out.println("==========");
TimeUnit.SECONDS.sleep(5);
}*/
TimeUnit.SECONDS.sleep(15);
//12s后shutdown
basicThreadPool.shutdown();
TimeUnit.SECONDS.sleep(1);
System.out.println("isShutdown:" + basicThreadPool.isShutdown());
//java.lang.IllegalStateException: 线程池已销毁
// System.out.println("QueueSize:" + basicThreadPool.getQueueSize());
//阻塞线程 - jStack -定位原因
Thread.currentThread().join();
}
}
Test-Out
//线程池动态扩张情况及任务执行情况: 输出
basicThreadPool.getActiveCount() = 2
basicThreadPool.getQueueSize() = 18
basicThreadPool.getCoreSize() = 4
basicThreadPool.getMaxSize() = 6
==========
basicThreadPool.getActiveCount() = 2
basicThreadPool.getQueueSize() = 18
basicThreadPool.getCoreSize() = 4
basicThreadPool.getMaxSize() = 6
==========
basicThreadPool.getActiveCount() = 4
thread-pool-0已启动
thread-pool-1已启动
basicThreadPool.getQueueSize() = 16
basicThreadPool.getCoreSize() = 4
basicThreadPool.getMaxSize() = 6
==========
basicThreadPool.getActiveCount() = 4
basicThreadPool.getQueueSize() = 14
basicThreadPool.getCoreSize() = 4
basicThreadPool.getMaxSize() = 6
==========
thread-pool-2已启动
thread-pool-3已启动
thread-pool-1已启动
thread-pool-0已启动
basicThreadPool.getActiveCount() = 6
basicThreadPool.getQueueSize() = 8
basicThreadPool.getCoreSize() = 4
basicThreadPool.getMaxSize() = 6
==========
basicThreadPool.getActiveCount() = 6
basicThreadPool.getQueueSize() = 8
basicThreadPool.getCoreSize() = 4
basicThreadPool.getMaxSize() = 6
==========
thread-pool-2已启动
thread-pool-5已启动
thread-pool-3已启动
thread-pool-4已启动
thread-pool-0已启动
thread-pool-1已启动
basicThreadPool.getActiveCount() = 6
basicThreadPool.getQueueSize() = 2
basicThreadPool.getCoreSize() = 4
basicThreadPool.getMaxSize() = 6
==========
basicThreadPool.getActiveCount() = 6
basicThreadPool.getQueueSize() = 2
basicThreadPool.getCoreSize() = 4
basicThreadPool.getMaxSize() = 6
==========
thread-pool-4已启动
thread-pool-3已启动
thread-pool-2已启动
thread-pool-5已启动
thread-pool-1已启动
thread-pool-0已启动
basicThreadPool.getActiveCount() = 6
basicThreadPool.getQueueSize() = 0
basicThreadPool.getCoreSize() = 4
basicThreadPool.getMaxSize() = 6
==========
basicThreadPool.getActiveCount() = 6
basicThreadPool.getQueueSize() = 0
basicThreadPool.getCoreSize() = 4
basicThreadPool.getMaxSize() = 6
==========
thread-pool-4已启动
thread-pool-3已启动
basicThreadPool.getActiveCount() = 5
basicThreadPool.getQueueSize() = 0
basicThreadPool.getCoreSize() = 4
basicThreadPool.getMaxSize() = 6
==========
basicThreadPool.getActiveCount() = 5
basicThreadPool.getQueueSize() = 0
basicThreadPool.getCoreSize() = 4
basicThreadPool.getMaxSize() = 6
==========
basicThreadPool.getActiveCount() = 4
basicThreadPool.getQueueSize() = 0
basicThreadPool.getCoreSize() = 4
basicThreadPool.getMaxSize() = 6
==========
basicThreadPool.getActiveCount() = 4
basicThreadPool.getQueueSize() = 0
basicThreadPool.getCoreSize() = 4
basicThreadPool.getMaxSize() = 6
==========
//线程池销毁 - 输出
thread-pool-0 已启动
thread-pool-1 已启动
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at java.lang.Thread.sleep(Thread.java:340)
at java.util.concurrent.TimeUnit.sleep(TimeUnit.java:386)
at com.zoro.concurrent.chapter08.ThreadPoolTest.lambda$main$0(ThreadPoolTest.java:19)
at com.zoro.concurrent.chapter08.threadpool.InternalTask.run(InternalTask.java:25)
at java.lang.Thread.run(Thread.java:748)
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at java.lang.Thread.sleep(Thread.java:340)
at java.util.concurrent.TimeUnit.sleep(TimeUnit.java:386)
at com.zoro.concurrent.chapter08.ThreadPoolTest.lambda$main$0(ThreadPoolTest.java:19)
at com.zoro.concurrent.chapter08.threadpool.InternalTask.run(InternalTask.java:25)
at java.lang.Thread.run(Thread.java:748)
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at java.lang.Thread.sleep(Thread.java:340)
at java.util.concurrent.TimeUnit.sleep(TimeUnit.java:386)
at com.zoro.concurrent.chapter08.ThreadPoolTest.lambda$main$0(ThreadPoolTest.java:19)
at com.zoro.concurrent.chapter08.threadpool.InternalTask.run(InternalTask.java:25)
at java.lang.Thread.run(Thread.java:748)
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at java.lang.Thread.sleep(Thread.java:340)
at java.util.concurrent.TimeUnit.sleep(TimeUnit.java:386)
at com.zoro.concurrent.chapter08.ThreadPoolTest.lambda$main$0(ThreadPoolTest.java:19)
at com.zoro.concurrent.chapter08.threadpool.InternalTask.run(InternalTask.java:25)
at java.lang.Thread.run(Thread.java:748)
isShutdown:true
Exception in thread "main" java.lang.IllegalStateException: 线程池已销毁
at com.zoro.concurrent.chapter08.threadpool.BasicThreadPool.getQueueSize(BasicThreadPool.java:204)
at com.zoro.concurrent.chapter08.ThreadPoolTest.main(ThreadPoolTest.java:42)
最后
存在问题 【待优化项】
- BasicThreadPool和Thread不应为继承关系,组合会更恰当;这样可以避免使用者直接调用Thread中的方法。
- 线程池的销毁功能并未返回未被处理的任务,这样会导致未被处理的任务丢弃。
- BasicThreadPool的构造函数参数过多,建议使用builder和设计模式对其封装或提供工厂方法进行构造。
- 线程池中的数量控制没有进行合法性校验,如:initSize不应该大于maxSize。
- 其他……