测试ThreadPoolExecutor的一个demo1

来源:互联网 发布:sas编程与数据挖掘商业案例 编辑:程序博客网 时间:2024/06/05 15:48

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

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再处理这个问题。

0 0