时间:2021-05-19
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方法
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。
线程池技术在并发时经常会使用到,java中的线程池的使用是通过调用ThreadPoolExecutor来实现的。ThreadPoolExecutor提供了四个构
ThreadPoolExecutor简介ThreadPoolExecutor是线程池类。对于线程池,可以通俗的将它理解为"存放一定数量线程的一个线程集合。线程池
jdk1.7.0_79在上一篇《ThreadPoolExecutor线程池原理及其execute方法》中提到了线程池ThreadPoolExecutor的原理以
ThreadPoolExecutor是JDK中的线程池实现,这个类实现了一个线程池需要的各个方法,它提供了任务提交、线程管理、监控等方法。下面是ThreadPo
通过ThreadPoolExecutor的方式创建线程池ThreadPoolExecutor构造方法:publicThreadPoolExecutor(intc