分享知识 传递快乐
1、newCachedThreadPool()
创建一个可缓存的线程池,如果线程池的规模超过了处理需求,将自动回收空闲线程,而当需求增加时,则可以自动添加新线程,线程池的规模不存在任何限制。
参考代码:
//newCachedThreadPool
public static void main(String[] args) {
ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
for (int i = 0; i < 10; i++) {
final int index = i;
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
cachedThreadPool.execute(new Runnable() {
public void run() {
System.out.println(index);
}
});
}
}
2、newFixedThreadPool(2)
创建一个固定长度的线程池,每当提交一个任务就创建一个线程,直到达到线程池的最大数量,超出的线程会在队列中等待。
参考代码:
//newFixedThreadPool
public static void main(String[] args) {
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);
for (int i = 0; i < 10; i++) {
final int index = i;
fixedThreadPool.execute(new Runnable() {
public void run() {
try {
System.out.println(index);
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
}
3、newScheduledThreadPool(2)
创建了一个固定长度的线程池,而且以延迟或定时的方式来执行任务,类似于Timer。
参考代码:
//newScheduledThreadPool
public static void main(String[] args) {
ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);
for (int i = 0; i < 10; i++) {
scheduledThreadPool.schedule(new Runnable() {
public void run() {
System.out.println("delay 3 seconds");
}
}, 3, TimeUnit.SECONDS);
}
}
4、newSingleThreadExecutor()
创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。
参考代码:
//newSingleThreadExecutor
public static void main(String[] args) {
ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
for (int i = 0; i < 10; i++) {
final int index = i;
singleThreadExecutor.execute(new Runnable() {
public void run() {
/* System.out.println(index);*/
try {
System.out.println(index);
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
}
5、newSingleThreadScheduledExecutor()
创建一个单例线程池,定期或延时执行任务。
参考代码:
//newSingleThreadScheduledExecutor
public class ThreadpoolsSingleThreadScheduled {
public static void main(String[]args) {
ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
for(int i=0;i<10;i++)
{
final int index=i;
scheduledExecutorService.schedule(new ThreadForpools(index),3, TimeUnit.SECONDS);
}
}
}
6、newWorkStealingPool(3)
创建一个带并行级别的线程池,并行级别决定了同一时刻最多有多少个线程在执行,如不穿如并行级别参数,将默认为当前系统的CPU个数。
参考代码:
//newWorkStealingPool
public class ThreadpoolsWorkStealingPool {
public static void main(String[] args) throws Exception {
// 设置并行级别为2,即默认每时每刻只有2个线程同时执行
ExecutorService executorService = Executors.newWorkStealingPool(3);
for (int i = 1; i <= 50; i++) {
final int count=i;
executorService.submit(new ThreadForpools(count));
}
while(true){
//主线程陷入死循环,来观察结果,否则是看不到结果的
}
}
}
——————————
如有不足请留言指正
相互学习,共同进步