Java多线程与并发应用-(8)-Callable和Future

来源:互联网 发布:mysql总是弹出taskeng 编辑:程序博客网 时间:2024/05/17 04:31

demo1: 使用FutureTask和Callable,获取一个线程的返回值。在获取返回值前可以做其他事,在Future.get()时阻塞,也可调用

get(long timeout, TimeUnit unit)方法设置在等待long时间后如果还没有返回值抛出异常。

package com.lipeng;import java.util.concurrent.Callable;import java.util.concurrent.FutureTask;public class FutureAndCallable1 {/** * 使用FutureTask和Callable * @param args */public static void main(String[] args)throws Exception  {//FutureTask实现了Runnalbe接口,所以可以用来构造Thread.//FutureTask实现了Callable接口,可以通过get获取线程返回值FutureTask<String> futureTask=new FutureTask<String>(new Callable<String>() {@Overridepublic String call() throws Exception {Thread.sleep(3000);return "hello";}});new Thread(futureTask).start();System.out.println("线程开始。。。。。。");//doSomeThingSystem.out.println(futureTask.get());}}

demo2:使用ExecutorService的submit(Callable c)方法

package com.lipeng;import java.util.concurrent.Callable;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;public class FutureAndCallable2 {/** * 使用ExecutorService的submit(Callable c)方法 * @param args */public static void main(String[] args)throws Exception  {ExecutorService executorService=Executors.newFixedThreadPool(3);Future<String> future=executorService.submit(new Callable<String>() {@Overridepublic String call() throws Exception {Thread.sleep(3000);return "hello";}});System.out.println("--------");System.out.println(future.get());}}

3 同时执行多次call方法,返回多个返回值,谁先执行完谁先返回

package com.lipeng;import java.util.Random;import java.util.concurrent.Callable;import java.util.concurrent.CompletionService;import java.util.concurrent.ExecutorCompletionService;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;public class FutureAndCallable2 {/** * 使用ExecutorService的submit(Callable c)方法 * @param args */public static void main(String[] args)throws Exception  {ExecutorService executorService=Executors.newFixedThreadPool(3);CompletionService<Integer> cs=new ExecutorCompletionService(executorService);for(int i=0;i<10;i++){final int j=i;cs.submit(new Callable<Integer>() {@Overridepublic Integer call() throws Exception {int time=new Random().nextInt(5000);Thread.sleep(time);return j;}});}System.out.println("---------------------------");for(int i=0;i<10;i++){int a=cs.take().get();System.out.println(a);}executorService.shutdown();}}


0 0
原创粉丝点击