版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/DWL0208/article/details/82286876
Java并发包java.util.concurrent下提供了对线程池的支持,Java通过Executors提供四种线程池。
1.FixedThreadPool 定长线程池,可控制线程最大并发数,超出的线程会在队列中等待
package com.mina.executorservice;
import java.util.concurrent.TimeUnit;
/**
* @program: minaproject
* @description: 处理器
* @author: daiwenlong
* @create: 2018-09-01 14:27
**/
public class ThreadHandler implements Runnable {
private int count;
public ThreadHandler(int count){
this.count = count;
}
public void run() {
System.out.println(Thread.currentThread().getName()+"------count:"+count);
try {//使线程睡眠,模拟线程阻塞情况
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
测试
package com.mina.executorservice;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @program: minaproject
* @description: 定长线程池
* @author: daiwenlong
* @create: 2018-09-01 14:25
**/
public class FixedThreadPool {
public static void main(String[] args) {
//定义一个5个线程的线程池
ExecutorService threadPool = Executors.newFixedThreadPool(5);
//执行10个任务
for(int i = 0;i < 10;i++){
threadPool.execute(new ThreadHandler(i));
}
}
}
运行结果
2.CachedThreadPool 缓存线程池,线程池线程数量随着处理任务的需要而增长,有空闲线程则使用空闲线程,无则创建新线程放入池中。
package com.mina.executorservice;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
/**
* @program: minaproject
* @description: 缓存线程池
* @author: daiwenlong
* @create: 2018-09-01 14:55
**/
public class CachedThreadPool {
public static void main(String[] args) {
ExecutorService threadPool = Executors.newCachedThreadPool();
for(int i = 0;i < 10;i++){
try {//主线程睡眠,等待部分线程完成任务
TimeUnit.MILLISECONDS.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
threadPool.execute(new ThreadHandler(i));
}
}
}
在运行结果中我们可以看到线程池创建了6个线程处理了10个任务。
3.SingleThreadExecutor 单线程池,只有一个线程。所有任务按照顺序执行。
package com.mina.executorservice;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @program: minaproject
* @description: 单线程池
* @author: daiwenlong
* @create: 2018-09-01 15:09
**/
public class SingleThreadExecutor {
public static void main(String[] args) {
ExecutorService threadPool = Executors.newSingleThreadExecutor();
for(int i =0;i<10;i++){
threadPool.execute(new ThreadHandler(i));
}
}
}
运行结果
4.ScheduledThreadPool 定时任务线程
package com.mina.executorservice;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* @program: minaproject
* @description: 定时任务线程池
* @author: daiwenlong
* @create: 2018-09-01 15:16
**/
public class ScheduledThreadPool {
public static void main(String[] args) {
ScheduledExecutorService threadPool = Executors.newScheduledThreadPool(2);
//每5秒执行一次
threadPool.scheduleAtFixedRate(new ThreadHandler(0),0,5, TimeUnit.SECONDS);
}
}
改造一下ThreadHandler,打印一下系统时间,可以看到每五秒执行了一次任务。