package com.example.demo.threadPool;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class ThreadPoolDemo {
public static void main(String[] args) throws InterruptedException {
ThreadPoolExecutor threadPoolExecutor = getThreadPoolExecutor3();
System.out.println("当前的线程数:"+threadPoolExecutor.getPoolSize());
for(int i=1;i<16;i++) {
final int n = i;
threadPoolExecutor.submit(new Runnable() {
@Override
public void run() {
System.out.println("线程"+n+"开始执行");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("线程"+n+"执行结束");
}
});
System.out.println("任务"+i+"提交成功");
}
Thread.sleep(500);
System.out.println("当前的线程数:"+threadPoolExecutor.getPoolSize());
System.out.println("队列中的线程数:"+threadPoolExecutor.getQueue().size());
Thread.sleep(15000);
System.out.println("当前的线程数:"+threadPoolExecutor.getPoolSize());
System.out.println("队列中的线程数:"+threadPoolExecutor.getQueue().size());
}
private static ThreadPoolExecutor getThreadPoolExecutor1() {
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5, 10,5, TimeUnit.SECONDS,new LinkedBlockingQueue<Runnable>());
return threadPoolExecutor;
}
private static ThreadPoolExecutor getThreadPoolExecutor2() {
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5, 10,5, TimeUnit.SECONDS,new LinkedBlockingQueue<Runnable>(3),new RejectedExecutionHandler() {
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
System.err.println("有任务被拒绝了");
}
});
return threadPoolExecutor;
}
private static ThreadPoolExecutor getThreadPoolExecutor3() {
//Executors.newFixedThreadPool(5);
//new ThreadPoolExecutor(5, 5,0L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>());
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5, 5,5, TimeUnit.SECONDS,new LinkedBlockingQueue<Runnable>());
return threadPoolExecutor;
}
private static ThreadPoolExecutor getThreadPoolExecutor4() {
//Executors.newCachedThreadPool();
//new ThreadPoolExecutor(0, Integer.MAX_VALUE,60L, TimeUnit.SECONDS,new SynchronousQueue<Runnable>());
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(0, Integer.MAX_VALUE,60, TimeUnit.SECONDS,new SynchronousQueue<Runnable>());
return threadPoolExecutor;
}
private static ThreadPoolExecutor getThreadPoolExecutor5() {
ScheduledThreadPoolExecutor scheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(5);
scheduledThreadPoolExecutor.schedule(new Runnable() {
@Override
public void run() {
System.out.println("定时任务开始执行");
}
}, 3, TimeUnit.SECONDS);
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(0, Integer.MAX_VALUE,60, TimeUnit.SECONDS,new SynchronousQueue<Runnable>());
return threadPoolExecutor;
}
}
Threadpool Demo
最新推荐文章于 2021-12-11 13:38:10 发布