第一种使用public FutureTask(Runnable runnable, V result)这个构造函数
@Slf4j public class FutureTaskExample1 { private static String result="no Done"; public static void main(String[] args) throws Exception { FutureTask<String> futureTask = new FutureTask<>(new Runnable() { @Override public void run() { result="Done"; log.info("do someThing in Runnable"); } },result); log.info("do someThing in main"); log.info("result:{}", result); new Thread(futureTask).start(); Thread.sleep(1000); log.info("result:{}", result); } }
第二种使用public FutureTask(Callable<V> callable)构造函数
@Slf4j
public class FutureTaskExample {
public static void main(String[] args) throws Exception {
FutureTask<String> futureTask = new FutureTask<>(new Callable<String>() {
@Override
public String call() throws Exception {
log.info("do someThing in Callable");
return "Done";
}
});
new Thread(futureTask).start();
log.info("do someThing in main");
Thread.sleep(1000);
String result = futureTask.get();
log.info("result:{}", result);
}
}