自定义线程池

本文介绍了一个自定义的阻塞线程池实现,包括线程池的初始化、任务执行、关闭方法及监控功能。该线程池采用ArrayBlockingQueue作为任务队列,并实现了自定义的线程工厂和拒绝策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


自定义线程池类,使用阻塞原理,多的任务等待
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class MyThreadPool {
    private ThreadPoolExecutor pool;

    //初始化线程池参数
    public MyThreadPool(int numberPools, int readyNumber) {//线程池总数,初始化数
        pool = new ThreadPoolExecutor(
                numberPools,
                numberPools, 1,
                TimeUnit.MILLISECONDS,
                new ArrayBlockingQueue<Runnable>(readyNumber),
                new CustomThreadFactory(),
                new ProcessingStrategy());
    }

    //关闭线程池,如果线程池中有任务,任务会丢失
    public void destory() {
        if (pool != null) {
            pool.shutdownNow();
        }
    }

    //缓冲方式
    private class CustomThreadFactory implements ThreadFactory {
        private AtomicInteger count = new AtomicInteger(0);
        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            String threadName = MyThreadPool.class.getSimpleName() + count.addAndGet(1);
            t.setName(threadName);
            return t;
        }
    }

    //任务添加到线程池的方式,处理策略
    private class ProcessingStrategy implements RejectedExecutionHandler {
        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
            try {
                executor.getQueue().put(r);// 核心改造点,offer改成put阻塞方法
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    //传递任务方法

    public void execute(Runnable runnable) {
        this.pool.execute(runnable);
    }

    //监控方法
    public void getMessage() {
        int poolSize = pool.getPoolSize();
        int size = pool.getQueue().size();
        long count = pool.getCompletedTaskCount();
        int active = pool.getActiveCount();
        System.out.println(String.format("线程池中线程数目:%d,队列中等待执行的任务数目:%d,已执行玩别的任务数目:%d, 活跃的线程数: %d", poolSize, size, count, active));
    }

}


测试类

      MyThreadPool pool = new MyThreadPool(40,20);//创建类
      pool.execute(new Runnable(){...});//传任务









附:主线程等待子线程代码
final CountDownLatch latch = new CountDownLatch(5);//设置线程数量
     new Thread(new Runnable() {
         @Override
         public void run() {
             latch.countDown();
             System.out.println("线程");
             try {
                 latch.await();
             } catch (InterruptedException e) {
                 e.printStackTrace();
             }
         }
     }).start();

 System.out.println("主线程");

 

 

 

 

 

 

线程停止


     

 main(){

        Thread main = Thread.currentThread();

        System.out.println(main.getName());

        main.interrupt();

        System.out.println("main线程已经退出了,但是不影响其他线程运行!");

  }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

小钻风巡山

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

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

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

打赏作者

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

抵扣说明:

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

余额充值