1、通过线程池提交FutrueTask异步任务
1 public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException { 2 3 long start = System.currentTimeMillis(); 4 ExecutorService executorService = Executors.newFixedThreadPool(3); 5 6 FutureTask<String> futureTask1 = new FutureTask<>(() -> { 7 TimeUnit.SECONDS.sleep(3); 8 return "futureTask1"; 9 }); 10 11 executorService.submit(futureTask1); 12 13 FutureTask<String> futureTask2 = new FutureTask<>(() -> { 14 TimeUnit.SECONDS.sleep(10); 15 return "futureTask2"; 16 }); 17 executorService.submit(futureTask2); 18 FutureTask<String> futureTask3 = new FutureTask<>(() -> { 19 TimeUnit.SECONDS.sleep(4); 20 return "futureTask3"; 21 }); 22 executorService.submit(futureTask3); 23 24 // 获取结果才是等待线程执行完成,如果不获取结果只是提交了任务 25 System.out.println(futureTask1.get()); 26 System.out.println(futureTask2.get()); 27 System.out.println(futureTask3.get()); 28 // FutrueTask接口一旦调用了get()方法,就会一直等待计算结果,容易造成线程阻塞 29 // get()方法一般放在程序后面 30 // 或者指定等待时间 31 System.out.println(futureTask2.get(3, TimeUnit.SECONDS)); // 会抛出异常 32 33 executorService.shutdown(); 34 35 long end = System.currentTimeMillis(); 36 37 System.out.println(end - start); 38 }
2、轮询获取FutrueTask的处理结果
要想FutrueTask的任务尽量不阻塞其他线程任务,应该把get()放到后面,并且采用轮询的方法获取计算结果
1 public static void main(String[] args) { 2 ExecutorService executorService = Executors.newFixedThreadPool(3); 3 try { 4 FutureTask<String> futureTask = new FutureTask<>(() -> { 5 TimeUnit.SECONDS.sleep(5); 6 return "futureTask"; 7 }); 8 9 executorService.submit(futureTask); 10 11 System.out.println("执行其他任务..."); 12 13 // 轮询耗费资源 14 while (true) { 15 if (futureTask.isDone()) { 16 System.out.println(futureTask.get()); 17 break; 18 } else { 19 TimeUnit.MILLISECONDS.sleep(500); 20 System.out.println("程序处理中,勿催"); 21 } 22 } 23 24 } catch (Exception e) { 25 e.printStackTrace(); 26 } finally { 27 executorService.shutdown(); 28 } 29 }
标签:JUC,get,System,FutrueTask,println,线程,FutureTask,executorService,out From: https://www.cnblogs.com/zhaohan258/p/18233849