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

时间:2021-02-26 18:03:26

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>() {
@Override
public String call() throws Exception {
Thread.sleep(3000);
return "hello";
}
});
new Thread(futureTask).start();
System.out.println("线程开始。。。。。。");
//doSomeThing
System.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>() {
@Override
public 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>() {
@Override
public 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();
}

}