0
点赞
收藏
分享

微信扫一扫

java: FutureTask的用法


package com.example.app;

import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;

public class FutureTaskTest {
public static void main(String[] args) throws Exception {
/* Callable<Integer> myCallable= new Callable<Integer>() {
@Override
public Integer call() throws Exception {
return new Random().nextInt(100);
}
};*/
Callable<Integer> myCallable = () -> {
System.out.println("in async task......");
Thread.sleep(2000);
return new Random().nextInt(100);
};

FutureTask<Integer> myTask =new FutureTask<>(myCallable);
new Thread(myTask).start();
System.out.println("in main thread......");

System.out.println(myTask.get());
//System.out.println(myTask.get(1000, TimeUnit.MILLISECONDS));
System.out.println("will exit.....");
}



}


说明: get()方法是阻塞的,直到拿到任务的结果才会返回。而带超时时间的get方法,如果达到设定的时间而没有拿到任务的结果会抛出TimeoutException


举报

相关推荐

0 条评论