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;}@Overridepublic 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();}
}
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.tpcf.cn/web/94114.html
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!