通过线程池开启多线程,并发执行任务。
新建任务类,实现 Callable 接口,参数通过构造方法传入。通过 executor 的 submit() 方法进行执行。
如果需要获取执行的返回结果,可以创建 FutureTask 对象,将任务类传入,调用 get() 方法获取执行结果,这个方法会阻塞程序,待获得返回值后才继续执行。
通常需要等待所有线程执行完毕才进行后续操作,调用 executor 的 shutdown() 方法,该线程池不会再继续接受任务,之前接受的任务会继续执行,
可以通过自身的 isTerminated() 方法判断是否全部执行完毕,或者 awaitTermination() 方法进行判断,或者 FutureTask 的 get() 方法。
1 public class MyExecutor { 2 3 private static ExecutorService executorService = Executors.newFixedThreadPool(3); 4 private static ExecutorService executorService2 = Executors.newFixedThreadPool(3); 5 6 static class MyTask implements Callable<Boolean> { 7 8 private String taskID; 9 10 public MyTask(String taskID) { 11 this.taskID = taskID; 12 } 13 14 @Override 15 public Boolean call() throws Exception { 16 if (taskID.equals("10")) { 17 System.out.println("第十次执行出错!"); 18 throw new RuntimeException("抛出运行时异常!"); 19 } 20 System.out.println(Thread.currentThread().getName()); 21 System.out.println("taskID :" + taskID); 22 Thread.sleep(1000); 23 return true; 24 } 25 } 26 27 static class MyTaskUUID implements Callable<String> { 28 29 private int str; 30 31 public MyTaskUUID(int str) { 32 this.str = str; 33 } 34 35 @Override 36 public String call() throws Exception { 37 String result = UUID.randomUUID().toString().replace("-", ""); 38 Thread.sleep(1000); 39 System.out.println("MyTaskUUID第" + str + "次执行~"); 40 return result + str * 100; 41 } 42 } 43 44 private static void testExecutors() { 45 for (int i = 0; i < 15; i++) { 46 if (i % 2 == 0) { 47 executorService.submit(new MyTask(String.valueOf(i))); 48 System.out.println("偶数线程池执行~"); 49 } else { 50 executorService2.submit(new MyTask(String.valueOf(i))); 51 System.out.println("奇数线程池执行~"); 52 } 53 System.out.println(i); 54 } 55 executorService.shutdown(); 56 executorService2.shutdown(); 57 try { 58 executorService.awaitTermination(1, TimeUnit.HOURS); 59 System.out.println("偶数线程执行完毕~"); 60 } catch (InterruptedException e) { 61 System.out.println(e.getMessage()); 62 } 63 while (true) { 64 if (executorService2.isTerminated()) { 65 System.out.println("奇数线程池执行完毕~"); 66 break; 67 } 68 } 69 } 70 71 private static void testFutureTask() { 72 Map<String, FutureTask<String>> map = new HashMap<>(); 73 for (int i = 0; i < 15; i++) { 74 FutureTask<String> task = new FutureTask<>(new MyTaskUUID(i)); 75 map.put(String.valueOf(i), task); 76 executorService.submit(task); 77 System.out.println(i); 78 } 79 executorService.shutdown(); 80 while (true) { 81 if (executorService.isTerminated()) { 82 break; 83 } 84 } 85 HashMap<String, String> resMap = new HashMap<>(); 86 for (String key : map.keySet()) { 87 try { 88 resMap.put(key, map.get(key).get()); 89 } catch (Exception e) { 90 System.out.println(e.getMessage()); 91 } 92 } 93 System.out.println(resMap); 94 } 95 96 public static void main(String[] args) { 97 testExecutors(); 98 testFutureTask(); 99 System.out.println("over~~"); 100 } 101 }