Coding面试题之手写线程池

原理图

JDK线程池原理

实现代码

1.线程类(PoolThread

这个类用于执行任务队列中的任务。

java 复制代码
public class PoolThread extends Thread {
    private final Queue<Runnable> taskQueue;
    private boolean isStopped = false;

    public PoolThread(Queue<Runnable> queue) {
        taskQueue = queue;
    }

    public void run() {
        while (!isStopped()) {
            try {
                Runnable runnable;
                synchronized (taskQueue) {
                    while (taskQueue.isEmpty()) {
                        taskQueue.wait();
                    }
                    runnable = taskQueue.poll();
                }
                runnable.run();
            } catch (Exception e) {
                // 异常处理
            }
        }
    }

    public synchronized void stopThread() {
        isStopped = true;
        this.interrupt(); // 中断线程
    }

    public synchronized boolean isStopped() {
        return isStopped;
    }
}

2.线程池类(ExtendedThreadPool

这个类用于管理线程和任务的分配。

java 复制代码
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Timer;
import java.util.TimerTask;

public class ExtendedThreadPool {
    private final Queue<Runnable> taskQueue;
    private final List<PoolThread> threads;
    private boolean isStopped;

    private int maxNumThreadSize;
    private int minNumThreadSize;
    private int keepAliveTime;
    private Timer maintainTimer;

    public ExtendedThreadPool(int minNumThreadSize, int maxNumThreadSize, int keepAliveTime) {
        this.minNumThreadSize = minNumThreadSize;
        this.maxNumThreadSize = maxNumThreadSize;
        this.keepAliveTime = keepAliveTime;
        this.taskQueue = new LinkedList<>();
        this.threads = new ArrayList<>();
        this.isStopped = false;
        this.maintainTimer = new Timer();

        for (int i = 0; i < this.minNumThreadSize; i++) {
            threads.add(new PoolThread(taskQueue));
        }

        for (PoolThread thread : threads) {
            thread.start();
        }

        maintainThreadPool();
    }

    public synchronized void execute(Runnable task) {
        if (this.isStopped) throw new IllegalStateException("ThreadPool is stopped");

        this.taskQueue.add(task);
        this.taskQueue.notify();

        if (threads.size() < maxNumThreadSize) {
            PoolThread newThread = new PoolThread(taskQueue);
            threads.add(newThread);
            newThread.start();
        }
    }

private void maintainThreadPool() {
    maintainTimer.schedule(new TimerTask() {
        @Override
        public void run() {
            synchronized (taskQueue) {
                // 如果任务多于线程,且线程数小于最大线程数,则增加线程
                if (!taskQueue.isEmpty()  && taskQueue.size()> threads.size()  &&  threads.size() < maxNumThreadSize) {
                    PoolThread newThread = new PoolThread(taskQueue);
                    threads.add(newThread);
                    newThread.start();
                }

                // 检查线程是否超过空闲时间,如果是,则移除线程
                Iterator<PoolThread> iterator = threads.iterator();
                while (iterator.hasNext()) {
                    PoolThread thread = iterator.next();
                    if (thread.isIdleFor(keepAliveTime)) {
                        iterator.remove();
                        thread.stopThread();
                    }
                }
            }
        }
    }, 0, keepAliveTime * 1000);
}


    public synchronized void stop() {
        this.isStopped = true;
        for (PoolThread thread : threads) {
            thread.stopThread();
        }
        maintainTimer.cancel();
    }
}

上面的代码如何保证线程复用?

  1. 任务到达时唤醒: 当一个新任务被添加到队列中并且队列之前是空的,execute 方法会调用 taskQueue.notify();,这会唤醒一个正在等待的线程。被唤醒的线程随后会从队列中取出任务并执行。

  2. 线程不立即终止: 线程在执行完一个任务后不会立即终止。相反,它会再次检查队列是否有新的任务。如果有,线程会继续执行新的任务。

相关文章

【精选】线程池的核心参数和运行机制_线程池的核心参数以及工作机制-CSDN博客

线程池内运行的线程抛异常,线程池会怎么办_线程池线程异常后会结束线程吗-CSDN博客

相关推荐
熊大如如22 分钟前
Java 反射
java·开发语言
猿来入此小猿41 分钟前
基于SSM实现的健身房系统功能实现十六
java·毕业设计·ssm·毕业源码·免费学习·猿来入此·健身平台
goTsHgo1 小时前
Spring Boot 自动装配原理详解
java·spring boot
卑微的Coder1 小时前
JMeter同步定时器 模拟多用户并发访问场景
java·jmeter·压力测试
pjx9872 小时前
微服务的“导航系统”:使用Spring Cloud Eureka实现服务注册与发现
java·spring cloud·微服务·eureka
多多*2 小时前
算法竞赛相关 Java 二分模版
java·开发语言·数据结构·数据库·sql·算法·oracle
爱喝酸奶的桃酥2 小时前
MYSQL数据库集群高可用和数据监控平台
java·数据库·mysql
唐僧洗头爱飘柔95273 小时前
【SSM-SSM整合】将Spring、SpringMVC、Mybatis三者进行整合;本文阐述了几个核心原理知识点,附带对应的源码以及描述解析
java·spring·mybatis·springmvc·动态代理·ioc容器·视图控制器
骑牛小道士3 小时前
Java基础 集合框架 Collection接口和抽象类AbstractCollection
java
alden_ygq4 小时前
当java进程内存使用超过jvm设置大小会发生什么?
java·开发语言·jvm