CodeFarmer鲍帅
2020-04-26 21:22:40浏览 1749
一、队列选择
SynchronousQueue:队列中仅容纳一个元素,对其操作必须是放和取交替进行;
ArrayBlockingQueue:有界队列,初始化时必须指定容量大小,并且无法修改,先入先出原则。
LinkedBlockingQueue:无界队列,初始化时指定容量就是有界队列,未指定容量就是无边界的,其实是Integer.MAX_VALUE的容量,内部实现是链表,先入先出。
二、创建线程池的几种方式
1、创建一个可重用固定个数的线程池,以共享的无界队列方式(LinkedBlockingQueue)来运行这些线程。
public static void newFixedThreadPool(){
ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
for (int i = 0; i < 10; i++) {
executorService.execute(new Runnable() {
@Override
public void run() {
System.out.println("固长的线程池-" + Thread.currentThread().getName());
try {
Thread.sleep(2000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
}
2、创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行,默认LinkedBlockingQueue。
public static void newSingleThreadExecutor(){
ExecutorService executorService = Executors.newSingleThreadExecutor();
for (int i = 0; i < 10; i++) {
final int idx = i;
executorService.execute(new Runnable() {
@Override
public void run() {
System.out.println("单线程线程池-"+Thread.currentThread().getName() + "-" + idx);
}
});
}
}
3、创建一个可缓存的线程池,先看看池中有没有以前建立的线程,有的话,就直接使用,没有,就新创建一个线程执行,默认SynchronousQueue。
public static void newCacheThreadPool(){
ExecutorService executorService = Executors.newCachedThreadPool();
for (int i = 0; i < 10; i++) {
try {//验证线程被复用
Thread.sleep(1000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
executorService.execute(new Runnable() {
@Override
public void run() {
System.out.println("可缓存的线程池-" + Thread.currentThread().getName());
}
});
}
}
4、可定时调度的线程池,默认DelayedWorkQueue。
public static void newScheduledThreadPool(){
ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(3);
scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
System.out.println("定长周期调度线程-" + Thread.currentThread().getName());
}
}, 1, 3, TimeUnit.SECONDS);
}
5、自定义线程池:corePoolSize maximumPoolSize keepAliveTime blockingQueue
public static void newThreadPoolExecutor(){
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(3, 3,
1, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(10));
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println("线程-" + Thread.currentThread().getName());
}
};
for (int i = 0; i < 10; i++) {
threadPoolExecutor.execute(runnable);
}
threadPoolExecutor.shutdown();
}