首页 > 代码库 > java 并发runable,callable,future,futureTask
java 并发runable,callable,future,futureTask
转载自:http://www.cnblogs.com/dolphin0520/p/3949310.html
package future_call; import java.util.concurrent.Callable; /** * Created by luozhitao on 2017/8/10. */ public class Task implements Callable<Integer> { // @Override public Integer call() throws Exception { System.out.println("子线程在进行计算"); Thread.sleep(10000); System.out.println("子线程睡眠完毕"); int sum=0; for (int i=0;i<100;i++){ sum+=i; } return sum; } }
1.使用Callable+Future
package future_call; import java.util.concurrent.*; /** * Created by luozhitao on 2017/8/10. */ public class Task_test { public static void main(String [] args){ ExecutorService executorService= Executors.newCachedThreadPool(); Task task=new Task(); Future<Integer> future=null; try{ // executorService future=executorService.submit(task); System.out.println("线程池关闭之前"); executorService.shutdown(); System.out.println("线程池关闭之后"); }catch (RejectedExecutionException e){System.out.println(e);} try{ Thread.sleep(1000); }catch (InterruptedException e){e.printStackTrace();} System.out.println("主线程在进行计算"); try{ System.out.println(future.get()); }catch (InterruptedException e){e.printStackTrace();} catch (ExecutionException e){e.printStackTrace();} } }
2.使用Callable+FutureTask
package future_call; import java.util.concurrent.*; /** * Created by luozhitao on 2017/8/10. */ public class future_task1 { public static void main(String [] args){ ExecutorService executorService= Executors.newCachedThreadPool(); Task task=new Task(); FutureTask<Integer> futureTask=new FutureTask<Integer>(task); try { /* executorService.submit(futureTask); executorService.shutdown(); */ Thread thread=new Thread(futureTask); thread.start(); }catch (RejectedExecutionException e){e.printStackTrace();} try { Thread.sleep(1000); System.out.println("主线程睡眠完毕"); }catch (InterruptedException e){e.printStackTrace();} try{ System.out.println(futureTask.get()); }catch (InterruptedException e){e.printStackTrace();}catch (ExecutionException e){e.printStackTrace();} } }
java 并发runable,callable,future,futureTask
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。