在多线程的开发中我们一般都会使用线程池,但是大家对于线程池的参数或许不是很了解。下面我们就来共同学习下:
// ThreadPoolExecutor extends AbstractExecutorService
// AbstractExecutorService implements ExecutorService
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory) {
}
参数释义:
- corePoolSize:核心线程数
- maximumPoolSize:最大线程数
- keepAliveTime:当线程数大于核心线程数时,空闲线程存活时间
- unit:时间单位
- workQueue:保存等待执行的任务队列
- threadFactory:线程工厂,可以省略,省略的话,那就使用默认的
当我们手动设置一个线程池,其核心线程数为2,最大线程数为4,我们提交四个线程,观察其输出:
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.time.LocalDateTime;
class Thread1 implements Runnable {
@Override
public void run() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(LocalDateTime.now() + ":Thread1");
}
}
class Thread2 implements Runnable {
@Override
public void run() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(LocalDateTime.now() + ":Thread2");
}
}
class Thread3 implements Runnable {
@Override
public void run() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(LocalDateTime.now() + ":Thread3");
}
}
class Thread4 implements Runnable {
@Override
public void run() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(LocalDateTime.now() + ":Thread4");
}
}
public class ThreadDemo {
static ThreadPoolExecutor executor = new ThreadPoolExecutor(2, 4,
60L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<>());
public static void main(String[] args) {
Thread1 thread1 = new Thread1();
Thread2 thread2 = new Thread2();
Thread3 thread3 = new Thread3();
Thread4 thread4 = new Thread4();
executor.execute(thread1);
executor.execute(thread2);
executor.execute(thread3);
executor.execute(thread4);
executor.shutdown();
}
}
输出:
2021-06-23T10:53:08.456:Thread2
2021-06-23T10:53:08.456:Thread1
2021-06-23T10:53:13.460:Thread3
2021-06-23T10:53:13.460:Thread4
当线程池核心数量不够时,新加入的任务会被存放在队列中,如果队列存满了,线程池会创建更多的线程,直到maximumPoolSize。如果还不足以处理新的任务,则面临一个丢弃策略,默认的丢弃策略是抛异常!