测试ThreadPoolExecutor的一个demo1

本文通过一个具体的Java示例,展示了线程池如何处理超出核心线程数的任务,并介绍了当任务队列满时线程池的行为。通过该示例,读者可以了解线程池在不同情况下的工作原理。

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

下面的例子测试的是线程池如何针对池化进行处理

package cn.test.concurrent;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ThreaPoolExepcutorDemo {
static ExecutorService tpe = new ThreadPoolExecutor(3, 5, 10,
TimeUnit.MILLISECONDS, new ArrayBlockingQueue(3),
new RejectedExecutionHandler() {
@Override
public void rejectedExecution(Runnable r,
ThreadPoolExecutor executor) {
Tpe tr = (Tpe) r;
System.out.println(tr.i + "Execute rejected");
throw new RuntimeException("异常了");
}
});
public static void main(String[] args) {
int i = 0;
tpe.execute(new Tpe(++i));
tpe.execute(new Tpe(++i));
tpe.execute(new Tpe(++i));
System.out.println("核心池满");
tpe.execute(new Tpe(++i));
tpe.execute(new Tpe(++i));
tpe.execute(new Tpe(++i));
System.out.println("队列满");
tpe.execute(new Tpe(++i));
tpe.execute(new Tpe(++i));
System.out.println("最大池满");
tpe.execute(new Tpe(++i));
tpe.execute(new Tpe(++i));
}
}


class Tpe implements Runnable {
public int i = 0;


public Tpe(int id) {
this.i = id;
}


@Override
public void run() {
System.out.println("线程" + i + "启动了。。。。");
while (true) {
}
}

}

测试结果,第9个线程就会被拒绝。第10个没有显示出来,456线程存在队列中。

心得:通过上面测试发现线程池的基础处理方式。

        问题说明:目前核心池线程1、2、3在处理业务,超过核心池的线程7、8也在处理业务,如果说核心池此时有一个空闲了,那么它会等还是销毁?,如果核心池中有一个销毁,那么7.8中是否有一个线程会转变为核心池,那么下个demo再处理这个问题。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值