java 自定义简单的线程池

java 自定义简单的线程池

/**
 * 简单的线程池实现类
 *
 * @author 作者名
 * @version 版本号
 * @since 创建时间
 */

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicBoolean;
 /**
  * 自定义简单的线程池
  */
class SimpleThreadPool {

    /**
     * 任务队列
     */
    private final BlockingQueue<Runnable> taskQueue;

    /**
     * 线程数组
     */
    private final Thread[] threads;

    /**
     * 线程池运行状态标识,true表示运行中,false表示已停止
     */
    private final AtomicBoolean running = new AtomicBoolean(true);

    /**
     * 构造方法,创建指定大小的线程池
     *
     * @param poolSize 线程池大小
     */
    public SimpleThreadPool(int poolSize) {
        taskQueue = new LinkedBlockingQueue<>();
        threads = new Thread[poolSize];
        for (int i = 0; i < poolSize; i++) {
            threads[i] = new Thread(() -> {
                while (running.get() || !taskQueue.isEmpty()) {
                    try {
                        taskQueue.take().run();
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    }
                }
            });
            threads[i].start();
        }
    }

    /**
     * 执行任务
     *
     * @param task 要执行的任务
     * @throws IllegalStateException 如果线程池已停止,则抛出此异常
     */
    public void execute(Runnable task) {
        if (running.get()) {
            taskQueue.offer(task);
        } else {
            throw new IllegalStateException("Thread pool is not running.");
        }
    }

    /**
     * 关闭线程池
     * 将running设置为false,并向任务队列中添加空任务,以便线程退出循环
     */
    public void shutdown() {
        running.set(false);
        for (Thread thread : threads) {
            taskQueue.offer(() -> {});
        }
    }
}

/**
 * 示例任务类,实现Runnable接口
 *
 * @author 作者名
 * @version 版本号
 * @since 创建时间
 */
class ExampleTask implements Runnable {
    /**
     * 任务编号
     */
    private final int id;

    /**
     * 构造方法
     *
     * @param id 任务编号
     */
    public ExampleTask(int id) {
        this.id = id;
    }

    @Override
    public void run() {
        System.out.println("Task " + id + " is running on thread " + Thread.currentThread().getName());
    }
}

/**
 * 测试类
 *
 * @author 作者名
 * @version 版本号
 * @since 创建时间
 */
public class Test {
    /**
     * 主方法
     *
     * @param args 命令行参数
     */
    public static void main(String[] args) {
        SimpleThreadPool pool = new SimpleThreadPool(5);

        for (int i = 0; i < 10; i++) {
            pool.execute(new ExampleTask(i));
        }

        pool.shutdown();
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

潇凝子潇

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值