05-Java通过Executors提供四种线程池

时间:2023-02-25 11:57:05

Java通过Executors提供四种线程池,分别为:
1. newCachedThreadPool创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。
2. newFixedThreadPool 创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。
3. newScheduledThreadPool 创建一个定长线程池,支持定时及周期性任务执行。
4. newSingleThreadExecutor 创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。

(1) newCachedThreadPool
创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。示例代码如下:

https://www.cnblogs.com/webglcn/p/5265901.html

package lcc.json.test;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadPoolExecutorTest {
public static void main(String[] args) {

ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
for (int i = 0; i < 10; i++) {
final int index = i;
try {
Thread.sleep(index * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}

cachedThreadPool.execute(new Runnable() {
public void run() {
System.out.println(Thread.currentThread().getName()+"="+index +"");
}
});

System.out.println("线程池"+cachedThreadPool.toString());
}
}
}

运行结果

pool-1-thread-1=0
线程池java.util.concurrent.ThreadPoolExecutor@70dea4e[Running, pool size = 1, active threads = 0, queued tasks = 0, completed tasks = 1]
pool-1-thread-1=1
线程池java.util.concurrent.ThreadPoolExecutor@70dea4e[Running, pool size = 1, active threads = 0, queued tasks = 0, completed tasks = 1]
线程池java.util.concurrent.ThreadPoolExecutor@70dea4e[Running, pool size = 1, active threads = 0, queued tasks = 0, completed tasks = 2]
pool-1-thread-1=2
pool-1-thread-1=3
线程池java.util.concurrent.ThreadPoolExecutor@70dea4e[Running, pool size = 1, active threads = 1, queued tasks = 0, completed tasks = 3]
pool-1-thread-1=4
线程池java.util.concurrent.ThreadPoolExecutor@70dea4e[Running, pool size = 1, active threads = 1, queued tasks = 0, completed tasks = 4]
线程池java.util.concurrent.ThreadPoolExecutor@70dea4e[Running, pool size = 1, active threads = 0, queued tasks = 0, completed tasks = 5]
pool-1-thread-1=5
线程池java.util.concurrent.ThreadPoolExecutor@70dea4e[Running, pool size = 1, active threads = 0, queued tasks = 0, completed tasks = 6]
pool-1-thread-1=6
pool-1-thread-1=7
线程池java.util.concurrent.ThreadPoolExecutor@70dea4e[Running, pool size = 1, active threads = 0, queued tasks = 0, completed tasks = 7]
pool-1-thread-1=8
线程池java.util.concurrent.ThreadPoolExecutor@70dea4e[Running, pool size = 1, active threads = 0, queued tasks = 0, completed tasks = 8]
线程池java.util.concurrent.ThreadPoolExecutor@70dea4e[Running, pool size = 1, active threads = 0, queued tasks = 0, completed tasks = 9]
pool-1-thread-1=9

线程池为无限大,当执行第二个任务时第一个任务已经完成,会复用执行第一个任务的线程,而不用每次新建线程。

(2) newFixedThreadPool
创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。示例代码如下:

package com.lcc3;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadPoolExecutorTest2 {
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(Thread.currentThread().getName()+"="+index +"");
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
System.out.println("线程池: "+fixedThreadPool.toString());
}
}
}

运行结果

pool-1-thread-1=0
线程池: java.util.concurrent.ThreadPoolExecutor@4e25154f[Running, pool size = 1, active threads = 1, queued tasks = 0, completed tasks = 0]
线程池: java.util.concurrent.ThreadPoolExecutor@4e25154f[Running, pool size = 2, active threads = 2, queued tasks = 0, completed tasks = 0]
线程池: java.util.concurrent.ThreadPoolExecutor@4e25154f[Running, pool size = 3, active threads = 3, queued tasks = 0, completed tasks = 0]
pool-1-thread-2=1
线程池: java.util.concurrent.ThreadPoolExecutor@4e25154f[Running, pool size = 3, active threads = 3, queued tasks = 1, completed tasks = 0]
pool-1-thread-3=2
线程池: java.util.concurrent.ThreadPoolExecutor@4e25154f[Running, pool size = 3, active threads = 3, queued tasks = 2, completed tasks = 0]
线程池: java.util.concurrent.ThreadPoolExecutor@4e25154f[Running, pool size = 3, active threads = 3, queued tasks = 3, completed tasks = 0]
线程池: java.util.concurrent.ThreadPoolExecutor@4e25154f[Running, pool size = 3, active threads = 3, queued tasks = 4, completed tasks = 0]
线程池: java.util.concurrent.ThreadPoolExecutor@4e25154f[Running, pool size = 3, active threads = 3, queued tasks = 5, completed tasks = 0]
线程池: java.util.concurrent.ThreadPoolExecutor@4e25154f[Running, pool size = 3, active threads = 3, queued tasks = 6, completed tasks = 0]
线程池: java.util.concurrent.ThreadPoolExecutor@4e25154f[Running, pool size = 3, active threads = 3, queued tasks = 7, completed tasks = 0]
pool-1-thread-1=3
pool-1-thread-2=4
pool-1-thread-3=5
pool-1-thread-1=6
pool-1-thread-2=7
pool-1-thread-3=8
pool-1-thread-1=9

因为线程池大小为3,每个任务输出index后sleep 2秒,所以每两秒打印3个数字。
定长线程池的大小最好根据系统资源进行设置。如Runtime.getRuntime().availableProcessors()

(3) newScheduledThreadPool
创建一个定长线程池,支持定时及周期性任务执行。延迟执行示例代码如下:

package com.lcc3;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class ThreadPoolExecutorTest2 {
public static void main(String[] args) {
ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);
System.out.println("delay 1 seconds, and excute every 3 seconds "+System.currentTimeMillis()/1000);
scheduledThreadPool.scheduleAtFixedRate(new Runnable() {
public void run() {
System.out.println("delay 1 seconds, and excute every 3 seconds "+System.currentTimeMillis()/1000);
}
}, 1, 3, TimeUnit.SECONDS);
}
}

运行结果

delay 1 seconds, and excute every 3 seconds 1517626186
delay 1 seconds, and excute every 3 seconds 1517626187
delay 1 seconds, and excute every 3 seconds 1517626190
delay 1 seconds, and excute every 3 seconds 1517626193
delay 1 seconds, and excute every 3 seconds 1517626196

表示延迟1秒后每3秒执行一次。

(4) newSingleThreadExecutor
创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。示例代码如下:

package com.lcc3;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadPoolExecutorTest2 {
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() {
try {
System.out.println(Thread.currentThread().getName()+"="+index +"");
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});

System.out.println("线程池"+singleThreadExecutor.toString());
}

}
}

运行结果

线程池线程池java.util.concurrent.Executors$FinalizableDelegatedExecutorService@4e25154f
pool-1-thread-1=0
线程池java.util.concurrent.Executors$FinalizableDelegatedExecutorService@4e25154f
线程池java.util.concurrent.Executors$FinalizableDelegatedExecutorService@4e25154f
线程池java.util.concurrent.Executors$FinalizableDelegatedExecutorService@4e25154f
线程池java.util.concurrent.Executors$FinalizableDelegatedExecutorService@4e25154f
线程池java.util.concurrent.Executors$FinalizableDelegatedExecutorService@4e25154f
线程池java.util.concurrent.Executors$FinalizableDelegatedExecutorService@4e25154f
线程池java.util.concurrent.Executors$FinalizableDelegatedExecutorService@4e25154f
线程池java.util.concurrent.Executors$FinalizableDelegatedExecutorService@4e25154f
线程池java.util.concurrent.Executors$FinalizableDelegatedExecutorService@4e25154f
pool-1-thread-1=1
pool-1-thread-1=2
pool-1-thread-1=3
pool-1-thread-1=4
pool-1-thread-1=5
pool-1-thread-1=6
pool-1-thread-1=7
pool-1-thread-1=8
pool-1-thread-1=9

结果依次输出,相当于顺序执行各个任务。

你可以使用JDK自带的监控工具来监控我们创建的线程数量,运行一个不终止的线程,创建指定量的线程,来观察:
工具目录:C:\Program Files\Java\jdk1.6.0_06\bin\jconsole.exe
运行程序做稍微修改:

package test;  
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadPoolExecutorTest {
public static void main(String[] args) {
ExecutorService singleThreadExecutor = Executors.newCachedThreadPool();
for (int i = 0; i < 100; i++) {
final int index = i;
singleThreadExecutor.execute(new Runnable() {
public void run() {
try {
while(true) {
System.out.println(index);
Thread.sleep(10 * 1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

效果如下:
05-Java通过Executors提供四种线程池

选择我们运行的程序:
05-Java通过Executors提供四种线程池