自定义线程池-有界队列

自定义线程池实现
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
 
 
/**
 * 自定义线程池
 */
public class MyLinkedThreadPool implements Runnable {
// static 必须得加
private static AtomicInteger count = new AtomicInteger(0);
public static void main(String[] args) throws InterruptedException {
LinkedBlockingQueue queue = new LinkedBlockingQueue<Runnable>();//指定无界队列
/*
 * ThreadPoolExecutor(int corePoolSize,    核心线程数即初始化时的线程数
         *       int maximumPoolSize,              最大线程数
         *       long keepAliveTime,               存活时间
         *       TimeUnit unit,                    单位
         *       BlockingQueue<Runnable> workQueue,任务队列
         *       ThreadFactory threadFactory,      线程工厂
         *       RejectedExecutionHandler handler) 拒绝执行的方法(拒绝策略)
 */
/*
 * 有界队列corePoolSize,如果线程数小于corePoolSize则会创建线程,
 * 到达corePoolSize后不会在继续创建线程,有任务就扔到队列里
 * 如果任务创建和处理的速度差异很大,无界队列会保持快速增长,
 * 直到内存耗尽宕机
 */
ThreadPoolExecutor pool = new ThreadPoolExecutor(5,
                10,
                120L,
                TimeUnit.SECONDS,
                queue
                //ThreadFactory threadFactory,
               // RejectedExecutionHandler handler)
                );
for (int i=0; i<20; i++) {
/*
 * 提交20个任务
 * corePoolSize为5,则先执行5个,剩余15个放入队列,
 *  等执行完5个,然后55个分批执行
 *
 */
pool.execute(new MyLinkedThreadPool());
}
Thread.sleep(1000);
System.out.println("队列size:" + queue.size());
Thread.sleep(2000);
}
@Override
public void run() {
int temp = count.incrementAndGet();
System.out.println("任务:" + temp);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值