自定义线程池

自定义线程池类,使用阻塞原理,多的任务等待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("主线程");

猜你喜欢

转载自blog.csdn.net/weixin_42660202/article/details/81207957