线程池 自定义线程工厂、自定义拒绝策略
作者:互联网
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @author xiufengd
* @date 2021/2/22 14:34
* 未来可期
* 线程池
*/
public class ExecutorTest {
public static class MyThread implements Runnable{
private Integer temp;
public MyThread(Integer temp){
this.temp=temp;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+":MyThread--------------"+temp);
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static class MyThread2 extends Thread{
@Override
public void run() {
}
}
public static class MyThread3 implements Callable<Integer>{
Integer temp;
public MyThread3(Integer temp){
this.temp=temp;
}
@Override
public Integer call() throws Exception {
System.out.println(Thread.currentThread().getName()+":MyThread3--------------"+temp);
Thread.sleep(3000);
return temp;
}
}
public static void main(String[] args) {
ExecutorService pools =
new ThreadPoolExecutor(3, 10, 10, TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>(5),new Factory(),new Handler());
try {
for (int i = 0; i < 50; i++) {
pools.execute(new MyThread(i));
}
} finally {
pools.shutdown();
}
}
private static class Factory implements ThreadFactory{
private AtomicInteger count = new AtomicInteger(0);
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r);
String threadName = "Factory----------------" + count.addAndGet(1);
t.setName(threadName);
System.out.println("线程" + threadName+"创建完成");
return t;
}
}
private static class Handler implements RejectedExecutionHandler{
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
MyThread myThread3 = (MyThread) r;
System.out.println(myThread3.temp+"被阻塞了");
// r.run();
}
}
}
标签:自定义,temp,拒绝,Thread,class,static,线程,new,public 来源: https://www.cnblogs.com/xiufengd/p/15933223.html