线程池ThreadPoolExecutor并行处理实现代码
作者:牛鼻子老赵
这篇文章主要介绍了线程池ThreadPoolExecutor并行处理实现代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
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方法
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。