public class ThreadMethod {
public static void main(String[] args) {
ThisLock thisLock = new ThisLock();
Thread thread1 = new Thread(() -> {
try {
thisLock.method1();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
thread1.start();
Thread thread2 = new Thread(() -> {
try {
thisLock.method2();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
thread2.start();
}
}
class ThisLock{
public synchronized void method1() throws InterruptedException {
System.out.println("method1");
Thread.sleep(10000);
}
public synchronized void method2() throws InterruptedException {
System.out.println("method2");
Thread.sleep(10000);
}
}
死锁产生的原因: 两个线程先得到了各自需要的锁, 当需要其它的锁时,发现锁被其它线程lock, 只能一直等待, 所以, 产生了死锁.
查看死锁:
案列分析
public class DeadLock {
private final Object lock = new Object();
private OtherService otherService;
public DeadLock(OtherService otherService) {
this.otherService = otherService;
}
public void s1() {
synchronized (lock) {
while (true) {
System.out.println("s1");
}
}
}
public void s2() {
synchronized (lock) {
while (true) {
System.out.println("s2");
otherService.m1();
}
}
}
}
public class OtherService {
private final Object lock = new Object();
private DeadLock deadLock;
public void m1() {
synchronized (lock) {
while (true) {
System.out.println("m1");
}
}
}
public void setDeadLock(DeadLock lock) {
this.deadLock = lock;
}
public void m2() {
synchronized (lock) {
while (true) {
System.out.println("m2");
deadLock.s1();
}
}
}
}
public class DeadLockDemo {
public static void main(String[] args) {
OtherService otherService = new OtherService();
DeadLock deadLock = new DeadLock(otherService);
otherService.setDeadLock(deadLock);
/**
* 1. otherService调用m1方法, 获得了OtherService中lock的锁.
* 2. otherService的m1方法, 调用了DeadLock的s2方法.
* 3. 而DeadLock的s2方法需要DeadLock的锁.
* 4. 但是DeadLock的锁, 已经被DeadLock的s2方法占用了.
* 5. 所有两个线程都在占用着对方需要的锁.
* 6. 所以造成了死锁.
*/
Thread thread1 = new Thread(() -> otherService.m2());
thread1.start();
Thread thread12 = new Thread(() -> deadLock.s2());
thread12.start();
}
}
public class ProduceConsumeV1 {
private int i = 0;
private volatile boolean isProduce = false;
private final Object lock = new Object();
public void produce() throws InterruptedException { //生产数据
synchronized (lock) {
if (isProduce) { // 存在生产数据, 等待消费
lock.wait();
} else { // 不存在生产数据, 生产数据; 唤醒消费线程, 进行消费.
System.out.println("p---> " + ++i);
lock.notify();
isProduce = true; // 修改是否生产标识.
}
}
}
public void consume() throws InterruptedException { //消费数据
synchronized (lock) {
if (isProduce) { //存在生产好的数据, 进行消费; 消费完, 唤醒生产线程, 生产数据
System.out.println("C---> " + i);
lock.notify();
isProduce = false; // 修改是否生产标识.
} else {
lock.wait();
}
}
}
public static void main(String[] args) {
ProduceConsumeV1 pc = new ProduceConsumeV1();
Thread thread1 = new Thread(() -> {
while (true) {
try {
pc.produce();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "P");
thread1.start();
Thread thread2 = new Thread(() -> {
while (true) {
try {
pc.consume();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "C");
thread2.start();
}
}
public class ProduceConsumeV2 {
private int i = 0;
private volatile boolean isProduce = false;
private final Object lock = new Object();
public void produce() throws InterruptedException { //生产数据
synchronized (lock) {
while (isProduce) { // 存在生产数据, 等待消费;
lock.wait(); // 使用while的目的, 若存在多个生产者wait.被消费者全部唤醒之后,
// 顺序往下执行, 可能会出现生产多次, 或者消费多次的情况.
}
// 不存在生产数据, 生产数据; 唤醒消费线程, 进行消费.
System.out.println(Thread.currentThread().getName() + "p---> " + ++i);
lock.notifyAll();
isProduce = true; // 修改是否生产标识.
}
}
public void consume() throws InterruptedException { //消费数据
synchronized (lock) {
while (!isProduce) {
lock.wait();
}
//存在生产好的数据, 进行消费; 消费完, 唤醒生产线程, 生产数据
System.out.println(Thread.currentThread().getName() + "C---> " + i);
lock.notifyAll();
isProduce = false; // 修改是否生产标识.
lock.wait();
}
}
public static void main(String[] args) {
ProduceConsumeV2 pc = new ProduceConsumeV2();
Stream.of("P1", "P2", "P3").forEach(n ->
new Thread(n) {
@Override
public void run() {
while (true) {
try {
pc.produce();
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start()
);
Stream.of("C1", "C2", "C3", "C4").forEach(n ->
new Thread(n) {
@Override
public void run() {
while (true) {
try {
pc.consume();
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start()
);
}
}
/**
* 1. 定义线程block超时异常.
*/
public class TimeOutException extends Exception {
public TimeOutException(String msg) {
super(msg);
}
}
/**
* 2. 定义一个Lock接口.
* 目的: 当synchronized多个线程在抢锁的时候,
* 未抢到锁的线程会一直block, 阻塞等待获取到线程执行权的机会。
* 也无法打断等待.
*/
public interface MyLock {
void lock() throws InterruptedException;
/**
* 等待mills, 还是没有获得锁, 就抛出TimeOutException.
*
* @param mills: 最大获取锁时长
* @throws InterruptedException
* @throws TimeOutException
*/
void lock(Long mills) throws InterruptedException, TimeOutException;
void unlock();
// 被block住的线程集合.
Collection<Thread> getBlockThread();
int getBlockThreadSize();
}
/**
* 3. 实现Lock接口.
*/
public class BooleanLock implements MyLock {
private Collection<Thread> blockThread = new ArrayList<>();
// lock -> true
// unLock -> false
private boolean initValue;
private Thread currentThread;
public BooleanLock() {
this.initValue = false;
}
@Override
public synchronized void lock() throws InterruptedException {
while (initValue) {
blockThread.add(Thread.currentThread());
this.wait();
}
/**
* 因为你已经获取到锁了, 所以从block队列中移除你.
*/
currentThread = Thread.currentThread();
blockThread.remove(this);
this.initValue = true;
}
@Override
public synchronized void lock(Long mills) throws InterruptedException, TimeOutException {
if(mills <= 0) {
lock();
}
long hasRemaining = mills;
long endTime = System.currentTimeMillis() + mills;
while (initValue) {
if (hasRemaining <= 0) {
throw new TimeOutException(Thread.currentThread().getName() + " is time out!");
}
blockThread.add(Thread.currentThread());
this.wait(mills);
hasRemaining = endTime - System.currentTimeMillis();
}
currentThread = Thread.currentThread();
blockThread.remove(this);
this.initValue = true;
}
@Override
public synchronized void unlock() {
// 保证只有自己unlock才能unlock掉; 不能其它的线程unlock掉不属于自己的线程
if (currentThread == Thread.currentThread()) {
this.initValue = false;
Optional.of(Thread.currentThread().getName() + "释放锁")
.ifPresent(System.out::println);
// 因为其它线程已经block住, 需要你完成了自己的任务的时候;
// 让其它的线程去唤醒, 获取执行权.
this.notifyAll();
}
}
@Override
public Collection<Thread> getBlockThread() {
// 防止数据被修改, unmodifiableCollection使得数据不可被修改.
return Collections.unmodifiableCollection(blockThread);
}
@Override
public int getBlockThreadSize() {
return blockThread.size();
}
}
/**
* 4. 测试Lock锁的功能.
*/
public class LockTest {
public static void main(String[] args) {
final BooleanLock booleanLock = new BooleanLock();
Stream.of("T1", "T2", "T3").forEach(item -> {
new Thread(() -> {
try {
booleanLock.lock(500L);
work();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (TimeOutException e) {
Optional.of(Thread.currentThread().getName() + " is time out")
.ifPresent(System.out::println);
} finally {
// 保证不管是否发生异常, 都能正常释放锁.
booleanLock.unlock();
}
}, item).start();
});
}
private static void work() throws InterruptedException {
Optional.of(Thread.currentThread().getName() + " is working....")
.ifPresent(System.out::println);
Thread.sleep(1_0000);
}
/**
* RunTime 程序停止hook(钩子)
*/
public class RunTimeDemo {
public static void main(String[] args) {
// 当服务停止的时候, 会调用此hook.
// kill -9 是强制杀死进程, 无法调用hook. 因此当我们是在使用其它的一些服务器的时候, 也注意不要使用
// kill -9; 因为服务器可能存在一些hook, 保存服务器停止的一些数据; 强制停止, 可能会造成一些数据的丢失等等
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
notifyShutDown();
}));
int index = 0;
while (true) {
try {
Thread.sleep(1_000);
System.out.println("It is working.....");
} catch (InterruptedException e) {
e.printStackTrace();
}
if (index++ > 20) {
throw new RuntimeException("Error");
}
}
}
// 在这里可以对于服务发生的错误, 通过RPC远程调用发送给对方服务.
private static void notifyShutDown() {
System.out.println("服务停止.......");
}
}
public class ThreadExceptionDemo {
public static void main(String[] args) {
Thread t = new Thread(() -> {
try {
Thread.sleep(1_000);
throw new ServiceException("线程异常");
} catch (InterruptedException e) {
e.printStackTrace();
}
});
// 得到线程出错的异常信息.
// 此代码无所谓放在start之前还是之后; 但是为了更加可读,建议放置在前面;先准备好相应的操作,再启动;
t.setUncaughtExceptionHandler((thread, e) -> {
System.out.println(e);
System.out.println(thread);
});
t.start();
}
}
public class ThreadStackTraceDemo {
public static void main(String[] args) {
new Test1().test();
}
}
class Test1 {
private Test2 test2 = new Test2();
public void test() {
test2.test();
}
}
class Test2 {
public void test() {
Arrays.asList(Thread.currentThread().getStackTrace()).stream()
.filter(s -> !s.isNativeMethod())
.forEach(e -> Optional.of(e.getClassName() + ":" + e.getMethodName() + ":" + e.getLineNumber()).ifPresent(System.out::println));
}
}
基础知识
常用API:
public class ThreadPoolV1 {
private int size; // 当前线程池大小
private final static int DEFAULT_SIZE = 10; // 默认线程池大小
private static volatile int sequence = 0;
private final static String THREAD_PREFIX = "THREAD_POOL_V1-"; // 线程前缀
private final static ThreadGroup GROUP = new ThreadGroup("pool_group");
private final static LinkedList<Runnable> TASK_QUEUE = new LinkedList<>(); //任务队列
private final static List<WorkerTask> THREAD_QUEUE = new ArrayList<>(); //任务执行队列
public ThreadPoolV1() {
this(DEFAULT_SIZE);
}
public ThreadPoolV1(int size) {
this.size = size;
init();
}
// 初始化线程池
private void init() {
for (int i = 0; i < size; i++) {
createWorkTask();
}
}
/**
* 创建DEFAULT_SIZE个线程用来执行任务, 一直存在于线程池中.
*/
private void createWorkTask() {
WorkerTask workerTask = new WorkerTask(GROUP, THREAD_PREFIX + (sequence++));
workerTask.start();
THREAD_QUEUE.add(workerTask);
}
/**
* 1. 把任务加入任务队列中; 但可能任务队列还没有任务时, 执行线程都wait住;
* 2. 现在有任务了, 需要把执行任务线程唤醒, 去执行任务.
*/
public void submit(Runnable runnable) {
synchronized (TASK_QUEUE) {
TASK_QUEUE.addLast(runnable);
TASK_QUEUE.notifyAll();
}
}
/*============== 线程状态========================*/
enum TaskState {
FREE, RUNNING, BLOCKED, DEAD
}
/*============== 执行线程========================*/
class WorkerTask extends Thread {
private volatile TaskState taskState = TaskState.FREE;
public WorkerTask(ThreadGroup group, String name) {
super(group, name);
}
public TaskState getTaskState() {
return this.taskState;
}
@Override
public void run() {
OUTER:
while (this.taskState != TaskState.DEAD) {
Runnable runnable;
synchronized (TASK_QUEUE) {
while (TASK_QUEUE.isEmpty()) { // 让获得锁的执行线程都wait.
try {
this.taskState = TaskState.BLOCKED;
TASK_QUEUE.wait();
} catch (InterruptedException e) {
break OUTER;
}
}
runnable = TASK_QUEUE.removeFirst();
}
if (runnable != null) {
this.taskState = TaskState.RUNNING;
runnable.run();
this.taskState = TaskState.FREE;
}
}
}
// 关闭线程
public void close() {
this.taskState = TaskState.DEAD;
}
}
public static void main(String[] args) {
ThreadPoolV1 threadPoolV1 = new ThreadPoolV1();
for (int i = 0; i < 40; i++) { // 模拟执行40个任务
threadPoolV1.submit(() -> {
System.out.println("The task " + Thread.currentThread() + "starting");
try {
Thread.sleep(1_000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("The task " + Thread.currentThread() + "finished");
});
}
}
}
public class ThreadPoolV1 {
private int size; // 当前线程池大小
private int taskQueueSize; // 当前线程池大小
private DiscardPolicy discardPolicy; //默认的拒绝策略
private final static int DEFAULT_SIZE = 10; // 默认线程池大小
private final static int DEFAULT_TASK_QUEUE_SIZE = 2000; // 默认任务队列最大长度
private static volatile int sequence = 0;
private final static String THREAD_PREFIX = "THREAD_POOL_V1-"; // 线程前缀
private final static ThreadGroup GROUP = new ThreadGroup("pool_group");
private final static LinkedList<Runnable> TASK_QUEUE = new LinkedList<>(); //任务队列
private final static List<WorkerTask> THREAD_QUEUE = new ArrayList<>();
public final static DiscardPolicy DEFAULT_DISCARD_POLICY = () -> { throw new DiscardException("拒绝此任务!");
};
private volatile boolean destroy = false; //线程池是否被释放.
public static int getDefaultSize() {
return DEFAULT_SIZE;
}
public ThreadPoolV1() {
this(DEFAULT_SIZE, DEFAULT_TASK_QUEUE_SIZE, DEFAULT_DISCARD_POLICY);
}
public ThreadPoolV1(int size, int taskQueueSize, DiscardPolicy discardPolicy) {
this.size = size;
this.taskQueueSize = taskQueueSize;
this.discardPolicy = discardPolicy;
init();
}
// 初始化线程池
private void init() {
for (int i = 0; i < size; i++) {
createWorkTask();
}
}
/**
* 创建DEFAULT_SIZE个线程用来执行任务, 一直存在于线程池中.
*/
private void createWorkTask() {
WorkerTask workerTask = new WorkerTask(GROUP, THREAD_PREFIX + (sequence++));
workerTask.start();
THREAD_QUEUE.add(workerTask);
}
/**
* 1. 判断此线程池是否可用.
* 2. 当任务队列 > 规定的队列大小时, 拒绝任务加入到队列中.
* 3. 把任务加入任务队列中; 但可能任务队列还没有任务时, 执行线程都wait住;
* 4. 现在有任务了, 需要把执行任务线程唤醒, 去执行任务.
*/
public void submit(Runnable runnable) {
if (destroy) {
throw new IllegalStateException("线程池已释放, 不可以再放入任务");
}
synchronized (TASK_QUEUE) {
if (TASK_QUEUE.size() > taskQueueSize) {
discardPolicy.discard();
}
TASK_QUEUE.addLast(runnable);
TASK_QUEUE.notifyAll();
}
}
public void shutdown() throws InterruptedException {
while (!TASK_QUEUE.isEmpty()) { //若队列中还存在任务, 等待任务执行.
Thread.sleep(50);
}
int threadQueueSize = THREAD_QUEUE.size();
while (threadQueueSize > 0) {
for (WorkerTask task : THREAD_QUEUE) { // 当执行线程为Block的时候, 没有任务需要执行, 可以关闭此执行线程.
if (task.getTaskState() == TaskState.BLOCKED) { // wait之后调用interrupt会抛出interruptException,
task.interrupt(); // 导致此线程的结束.
task.close();
threadQueueSize--;
} else {
Thread.sleep(100);
}
}
}
System.out.println("线程池被关闭");
this.destroy = true;
}
public int getSize() {
return size;
}
public int getTaskQueueSize() {
return taskQueueSize;
}
public boolean isDestroy() {
return destroy;
}
/*============== 拒绝策略========================*/
public static class DiscardException extends RuntimeException {
public DiscardException(String message) {
super(message);
}
}
public interface DiscardPolicy {
void discard() throws DiscardException;
}
/*============== 线程状态========================*/
enum TaskState { FREE, RUNNING, BLOCKED, DEAD
}
/*============== 执行线程========================*/
class WorkerTask extends Thread {
private volatile TaskState taskState = TaskState.FREE;
public WorkerTask(ThreadGroup group, String name) {
super(group, name);
}
public TaskState getTaskState() {
return this.taskState;
}
@Override
public void run() {
OUTER:
while (this.taskState != TaskState.DEAD) {
Runnable runnable;
synchronized (TASK_QUEUE) {
while (TASK_QUEUE.isEmpty()) { // 让获得锁的执行线程都wait.
try {
this.taskState = TaskState.BLOCKED;
TASK_QUEUE.wait();
} catch (InterruptedException e) {
break OUTER; //多重循环,直接使用标记退出循环.
}
}
runnable = TASK_QUEUE.removeFirst();
}
if (runnable != null) {
this.taskState = TaskState.RUNNING;
runnable.run();
this.taskState = TaskState.FREE;
}
}
}
// 关闭线程
public void close() {
this.taskState = TaskState.DEAD;
}
}
public static void main(String[] args) throws InterruptedException {
// ThreadPoolV1 threadPoolV1 = new ThreadPoolV1(6, 10, DEFAULT_DISCARD_POLICY); //拒绝策略
ThreadPoolV1 threadPoolV1 = new ThreadPoolV1();
for (int i = 0; i < 40; i++) { // 模拟执行40个任务
threadPoolV1.submit(() -> {
System.out.println("The task " + Thread.currentThread() + "starting");
try {
Thread.sleep(1_000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("The task " + Thread.currentThread() + "finished");
});
System.out.println("i: " + i);
}
Thread.sleep(10_000);
threadPoolV1.shutdown(); //关闭线程池
}
}
public class ThreadPoolV1 extends Thread {
private int size; // 当前线程池大小
private int taskQueueSize; // 当前线程池大小
private DiscardPolicy discardPolicy; //默认的拒绝策略
private final static int DEFAULT_TASK_QUEUE_SIZE = 2000; // 默认任务队列最大长度
private static volatile int sequence = 0;
private final static String THREAD_PREFIX = "THREAD_POOL_V1-"; // 线程前缀
private final static ThreadGroup GROUP = new ThreadGroup("pool_group");
private final static LinkedList<Runnable> TASK_QUEUE = new LinkedList<>(); //任务队列
private final static List<WorkerTask> THREAD_QUEUE = new ArrayList<>();
public final static DiscardPolicy DEFAULT_DISCARD_POLICY = () -> { throw new DiscardException("拒绝此任务!");
};
private volatile boolean destroy = false; //线程池是否被释放.
private int min; // 线程池最小线程数
private int max; // 线程池最大线程数
private int active; // 线程池活跃线程数
public ThreadPoolV1() {
this(4, 8, 12, DEFAULT_TASK_QUEUE_SIZE, DEFAULT_DISCARD_POLICY);
}
public ThreadPoolV1(int min, int active, int max, int taskQueueSize, DiscardPolicy discardPolicy) {
this.taskQueueSize = taskQueueSize;
this.discardPolicy = discardPolicy;
this.min = min;
this.active = active;
this.max = max;
init();
}
// 初始化线程池
private void init() {
for (int i = 0; i < this.min; i++) { // 初始化线程池, 最开始只创建min个线程.
createWorkTask();
}
this.size = min;
this.start();
}
/**
* 创建DEFAULT_SIZE个线程用来执行任务, 一直存在于线程池中.
*/
private void createWorkTask() {
WorkerTask workerTask = new WorkerTask(GROUP, THREAD_PREFIX + (sequence++));
workerTask.start();
THREAD_QUEUE.add(workerTask);
}
/**
* 1. 判断此线程池是否可用.
* 2. 当任务队列 > 规定的队列大小时, 拒绝任务加入到队列中.
* 3. 把任务加入任务队列中; 但可能任务队列还没有任务时, 执行线程都wait住;
* 4. 现在有任务了, 需要把执行任务线程唤醒, 去执行任务.
*/
public void submit(Runnable runnable) {
if (destroy) {
throw new IllegalStateException("线程池已释放, 不可以再放入任务");
}
synchronized (TASK_QUEUE) {
if (TASK_QUEUE.size() > taskQueueSize) {
discardPolicy.discard();
}
TASK_QUEUE.addLast(runnable);
TASK_QUEUE.notifyAll();
}
}
public void shutdown() throws InterruptedException {
while (!TASK_QUEUE.isEmpty()) { //若队列中还存在任务, 等待任务执行.
Thread.sleep(50);
}
synchronized (THREAD_QUEUE) {
int threadQueueSize = THREAD_QUEUE.size();
while (threadQueueSize > 0) {
for (WorkerTask task : THREAD_QUEUE) { // 当执行线程为Block的时候, 没有任务需要执行, 可以关闭此执行线程.
if (task.getTaskState() == TaskState.BLOCKED) { // wait之后调用interrupt会抛出interruptException,
task.interrupt(); // 导致此线程的结束.
task.close();
threadQueueSize--;
} else {
Thread.sleep(100);
}
}
}
}
System.out.println("线程池被关闭");
this.destroy = true;
}
public int getSize() {
return size;
}
public int getTaskQueueSize() {
return taskQueueSize;
}
public boolean isDestroy() {
return destroy;
}
public int getMin() {
return min;
}
public int getMax() {
return max;
}
public int getActive() {
return active;
}
@Override
public void run() {
while (!isDestroy()) {
System.out.printf("Pool min: %d, active: %d, max: %d, current: %d, queueSize:%d\n",
this.min, this.active, this.max, this.size, TASK_QUEUE.size());
try {
Thread.sleep(5_000L);
// 对执行线程扩容
if (TASK_QUEUE.size() > active && size < active) {
// 若任务队列大于active, 且当前线程数小于active.
// 说明: 任务多余active, 有必要扩容.
for (; this.size < this.active; this.size++) {
createWorkTask();
}
System.out.println("线程池扩容至Active");
} else if (TASK_QUEUE.size() > max && size < max) {
// 若任务队列大于active, 且当前线程数大于active.
// 说明: 任务多余active, 有必要扩容.
for (; this.size < this.max; this.size++) {
createWorkTask();
}
System.out.println("线程池扩容至Max");
}
// 对线程池减少执行线程数量
synchronized (THREAD_QUEUE) {
if (TASK_QUEUE.isEmpty() && size > active) {
int releaseSize = size - active;
Iterator<WorkerTask> iterator = THREAD_QUEUE.iterator();
while (iterator.hasNext()) {
if (releaseSize <= 0) {
break;
}
WorkerTask task = iterator.next();
task.close();
task.interrupt();
iterator.remove();
releaseSize--;
}
size = active;
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
/*============== 拒绝策略========================*/
public static class DiscardException extends RuntimeException {
public DiscardException(String message) {
super(message);
}
}
public interface DiscardPolicy {
void discard() throws DiscardException;
}
/*============== 线程状态========================*/
enum TaskState {
FREE, RUNNING, BLOCKED, DEAD
}
/*============== 执行线程========================*/
class WorkerTask extends Thread {
private volatile TaskState taskState = TaskState.FREE;
public WorkerTask(ThreadGroup group, String name) {
super(group, name);
}
public TaskState getTaskState() {
return this.taskState;
}
@Override
public void run() {
OUTER:
while (this.taskState != TaskState.DEAD) {
Runnable runnable;
synchronized (TASK_QUEUE) {
while (TASK_QUEUE.isEmpty()) { // 让获得锁的执行线程都wait.
try {
this.taskState = TaskState.BLOCKED;
TASK_QUEUE.wait();
} catch (InterruptedException e) { System.out.println("Closed.");
break OUTER;
}
}
runnable = TASK_QUEUE.removeFirst();
}
if (runnable != null) {
this.taskState = TaskState.RUNNING;
runnable.run();
this.taskState = TaskState.FREE;
} }
}
// 关闭线程
public void close() {
this.taskState = TaskState.DEAD;
}
}
public static void main(String[] args) throws InterruptedException {
// ThreadPoolV1 threadPoolV1 = new ThreadPoolV1(6, 10, DEFAULT_DISCARD_POLICY); //拒绝策略
ThreadPoolV1 threadPoolV1 = new ThreadPoolV1();
for (int i = 0; i < 80; i++) { // 模拟执行80个任务
threadPoolV1.submit(() -> {
System.out.println("The task " + Thread.currentThread() + "starting");
try {
Thread.sleep(1_000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("The task " + Thread.currentThread() + "finished");
});
}
Thread.sleep(10000);
threadPoolV1.shutdown(); //关闭线程池
}}