Java通过Executors提供四种线程池,分别为:
- newCachedThreadPool创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。
- newFixedThreadPool 创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。
- newScheduledThreadPool 创建一个定长线程池,支持定时及周期性任务执行。
- newSingleThreadExecutor 创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。
newSingleThreadExecutor :只有一个线程 一个一个的执行(单线程执行器)。
private static void singleThreadExecutor() {
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 {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
}
newScheduledThreadPool :延迟线程执行器。
private static void scheduledThreadPool() {
ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(2);
scheduledThreadPool.schedule(new Runnable() {
public void run() {
System.out.println("hehe cnn");
}
}, 1, TimeUnit.SECONDS);
// 延迟重复执行
scheduledThreadPool.scheduleAtFixedRate(new Runnable() {
public void run() {
System.out.println(3);
}
}, 1, 1, TimeUnit.SECONDS);
}
newFixedThreadPool :定长线程执行器。
private static void fixedThreadPool() {
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(2);
for (int i = 0; i < 10; i++) {
final int index = i;
fixedThreadPool.execute(new Runnable() {
public void run() {
System.out.println(index);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
}
newCachedThreadPool:可缓存的线程池。
private static void cachedThreadPool() throws InterruptedException {
// 创建一个可缓存的线程池
ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
for (int i = 0; i < 10; i++) {
final int index = i;
Thread.sleep(200);
cachedThreadPool.execute(new Runnable() {
public void run() {
System.out.println(index);
}
});
}
}