话不多说,直接上代码
package example.futureTask;
import com.alibaba.fastjson.JSONObject;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Callable;
/**
* @Description:
* @Date:
*/
public class TestFutureTask {
public static Map getUserScore()throws Exception {
Callable scoreCall =new Callable() {
@Override
public Integer call()throws Exception {
return getScore();
}
};
//CustomerFutureTask 是自定义的FutureTask类,也可以直接用原生的FutureTask类
CustomerFutureTask scoreFuture =new CustomerFutureTask<>(scoreCall);
new Thread(scoreFuture).start();
Callable orderCall =new Callable() {
@Override
public Integer call()throws Exception {
return getOrderCnt();
}
};
CustomerFutureTask orderFuture =new CustomerFutureTask<>(orderCall);
new Thread(orderFuture).start();
Map result =new HashMap<>();
result.put("score", scoreFuture.get());
result.put("orderCnt", orderFuture.get());
return result;
}
private static Integer getScore()throws InterruptedException {
Thread.sleep(200);
return 200;
}
private static Integer getOrderCnt()throws InterruptedException {
Thread.sleep(300);
return 300;
}
public static void main(String[] args)throws Exception {
long start = System.currentTimeMillis();
Map resultMap =getUserScore();
System.out.println(JSONObject.toJSON(resultMap));
long end = System.currentTimeMillis();
System.out.println("cost " + (end - start));
}
}
自定义一个FutureTask类:
package example.futureTask;
import java.util.concurrent.*;
/**
* @Description:
* @Date:
*/
public class CustomerFutureTaskimplements RunnableFuture {
private Callable callable;
private V result =null;
public CustomerFutureTask(Callable callable){
this.callable = callable;
}
@Override
public void run() {
try {
result =callable.call();
synchronized (this) {
this.notifyAll();//获取到值,唤醒全部等待线程
}
}catch (Exception e) {
e.printStackTrace();
}
}
@Override
public V get()throws InterruptedException {
if (result !=null)
return result;
synchronized (this) {
this.wait();//如果未获取到值,线程等待
}
return result;
}
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
return false;
}
@Override
public boolean isCancelled() {
return false;
}
@Override
public boolean isDone() {
return false;
}
@Override
public V get(long timeout, TimeUnit unit)throws InterruptedException, ExecutionException {
return null;
}
}