线程池ThreadPoolExecutor并行处理实现代码
作者:牛鼻子老赵 时间:2022-10-13 23:44:01
1、定义一个接口 Animal
package com.zh.vo;
public interface Animal {
void work();
}
2、定义一个实现类 Bird
package com.zh.vo;
public class Bird implements Animal {
@Override
public void work() {
int sum = 0;
for (int i = 0; i < 100000; i++) {
sum += i;
}
System.out.println("Bird calc: " + sum + " time: " + System.currentTimeMillis());
}
}
3、定义一个实现类 Cat
package com.zh.vo;
public class Cat implements Animal {
@Override
public void work() {
int sum = 0;
for (int i = 0; i < 100000; i++) {
sum += i;
}
System.out.println("Cat calc: " + sum + " time: " + System.currentTimeMillis());
}
}
4、定义一个实现类 Dog
package com.zh.vo;
public class Dog implements Animal {
@Override
public void work() {
int sum = 0;
for (int i = 0; i < 100000; i++) {
sum += i;
}
System.out.println("Dog calc: " + sum + " time: " + System.currentTimeMillis());
}
}
5、定义一个枚举类 AnimalEnum
package com.zh.enums;
import com.zh.vo.Bird;
import com.zh.vo.Cat;
import com.zh.vo.Dog;
public enum AnimalEnum {
CAT("cat", Cat.class), DOG("dog", Dog.class), BIRD("bird", Bird.class);
private String name;
private Class<?> clazz;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Class<?> getClazz() {
return clazz;
}
public void setClazz(Class<?> clazz) {
this.clazz = clazz;
}
private AnimalEnum(String name, Class<?> clazz) {
this.name = name;
this.clazz = clazz;
}
public static void main(String[] args) {
// System.out.println(getName(DOG));
// System.out.println(getClazz(DOG));
AnimalEnum[] values = AnimalEnum.values();
System.out.println(values);
}
}
6、定义一个操作类 AnimalUtil
package com.zh.utils;
import java.util.HashMap;
import java.util.Map;
import com.zh.enums.AnimalEnum;
import com.zh.vo.Animal;
public enum AnimalUtil {
INSTANCE;
private static Map<AnimalEnum, Animal> map = null;
private synchronized void init() {
map = new HashMap<AnimalEnum, Animal>();
AnimalEnum[] values = AnimalEnum.values();
for (AnimalEnum animalEnum : values) {
Animal newInstance = null;
try {
newInstance = (Animal)animalEnum.getClazz().newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
map.put(animalEnum, newInstance);
}
}
public Map<AnimalEnum, Animal> getEnumMaps() {
if (map == null || map.isEmpty()) {
init();
}
return map;
}
}
7、定义一个测试主类使用 Future、Callable
package com.zh;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import com.zh.enums.AnimalEnum;
import com.zh.utils.AnimalUtil;
import com.zh.vo.Animal;
/**
* @desc 测试线程池
* @author zhanhao
*/
public class ThreadPoolSubmitTest {
/**
* 定义线程池
*/
// Runtime.getRuntime().availableProcessors() * 2
private static ThreadPoolExecutor threadPoolExecutor =
new ThreadPoolExecutor(10, 20, 100, TimeUnit.MINUTES, new LinkedBlockingQueue<Runnable>());
/**
* @desc 执行主流程
* @param args
* @throws InterruptedException
* @throws ExecutionException
*/
public static void main(String[] args) throws InterruptedException, ExecutionException {
Map<String, Future<String>> futureMap = new HashMap<String, Future<String>>();
Set<Entry<AnimalEnum, Animal>> entrySet = AnimalUtil.INSTANCE.getEnumMaps().entrySet();
for (Entry<AnimalEnum, Animal> entry : entrySet) {
futureMap.put(entry.getKey().getName(), exec(entry.getKey()));
}
for (Entry<String, Future<String>> entry : futureMap.entrySet()) {
System.out.println(entry.getValue().get());
}
waitForAllThreadFinish();
threadPoolExecutor.shutdown();
}
/**
* @desc 讲任务提交到线程池中执行
* @param enums
* @return
*/
private static Future<String> exec(AnimalEnum enums) {
return threadPoolExecutor.submit(new Callable<String>() {
@Override
public String call() throws Exception {
Animal animal = AnimalUtil.INSTANCE.getEnumMaps().get(enums);
animal.work();
return Thread.currentThread().getName();
}
});
}
/**
* @desc 线程中有未完成的任务需等待完成
*/
private static void waitForAllThreadFinish() {
while (threadPoolExecutor.getQueue().size() > 0 || threadPoolExecutor.getActiveCount() > 0) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
8、执行结果
Dog calc: 704982704 time: 1574129306137
Bird calc: 704982704 time: 1574129306137
Cat calc: 704982704 time: 1574129306137
pool-1-thread-1
pool-1-thread-2
pool-1-thread-3
9、定义一个测试主类使用 Runnable
package com.zh;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import com.zh.enums.AnimalEnum;
import com.zh.utils.AnimalUtil;
import com.zh.vo.Animal;
/**
* @desc 测试线程池
* @author zhanhao
*/
public class ThreadPoolExecuteTest {
/**
* 定义线程池
*/
// Runtime.getRuntime().availableProcessors() * 2
private static ThreadPoolExecutor threadPoolExecutor =
new ThreadPoolExecutor(10, 20, 100, TimeUnit.MINUTES, new LinkedBlockingQueue<Runnable>());
/**
* @desc 执行主流程
* @param args
* @throws InterruptedException
* @throws ExecutionException
*/
public static void main(String[] args) throws InterruptedException, ExecutionException {
Set<Entry<AnimalEnum, Animal>> entrySet = AnimalUtil.INSTANCE.getEnumMaps().entrySet();
for (Entry<AnimalEnum, Animal> entry : entrySet) {
exec(entry.getKey());
}
waitForAllThreadFinish();
threadPoolExecutor.shutdown();
}
/**
* @desc 讲任务提交到线程池中执行
* @param enums
* @return
*/
private static void exec(AnimalEnum enums) {
threadPoolExecutor.execute(new Runnable() {
@Override
public void run() {
Animal animal = AnimalUtil.INSTANCE.getEnumMaps().get(enums);
animal.work();
System.out.println(Thread.currentThread().getName());
}
});
}
/**
* @desc 线程中有未完成的任务需等待完成
*/
private static void waitForAllThreadFinish() {
while (threadPoolExecutor.getQueue().size() > 0 || threadPoolExecutor.getActiveCount() > 0) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
10、执行结果
Bird calc: 704982704 time: 1574129356078
Dog calc: 704982704 time: 1574129356078
pool-1-thread-3
Cat calc: 704982704 time: 1574129356078
pool-1-thread-1
pool-1-thread-2
注:1、submit 方法可以有返回值 2、submit 底层调用execute方法
来源:https://www.cnblogs.com/zhanh247/p/11887510.html
标签:Thread,Pool,Executor,并行,处理
0
投稿
猜你喜欢
android实现文件下载功能
2022-07-29 18:03:10
spring aop execution表达式的用法
2023-08-22 05:39:24
Android中实现iOS中的毛玻璃效果
2023-01-27 01:44:14
Java DecimalFormat 保留小数位及四舍五入的陷阱介绍
2023-11-09 04:49:33
Java Redis Redisson配置教程详解
2022-10-13 06:32:39
在Java中String和Date、Timestamp之间的转换
2023-10-07 13:52:36
利用Java代码写一个并行调用模板
2023-07-04 16:00:39
.net(c#)中的new关键字详细介绍
2021-08-29 21:19:27
springboot项目快速搭建的方法步骤
2021-11-07 04:55:51
springBoot解决static和@Component遇到的bug
2022-12-31 01:23:27
聊聊Java 中的线程中断
2021-05-31 02:04:30
springboot过滤器和拦截器的实例代码
2021-09-14 04:53:17
java并发之原子操作类和非阻塞算法
2022-04-13 04:39:01
C# 多线程中经常访问同一资源可能造成哪些问题
2022-09-08 05:22:47
Springboot @Validated和@Valid的区别及使用详解
2023-05-30 18:40:25
Java 8中日期和时间的处理方法
2021-09-07 15:37:58
SpringBoot访问静态资源的配置及顺序说明
2022-07-18 13:53:31
Android实现图片拖拉功能
2023-03-27 14:57:51
Spring利用@Validated注解实现参数校验详解
2023-08-26 12:06:26
c#模拟银行atm机示例分享
2023-04-01 10:59:45