以下为一个使用FutureTask进行模拟预加载的代码:
package JavaDay6_02;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
/**
* @author myvina@qq.com
* @date 18-6-2 上午9:53
*/
public class Demo2 {
private final FutureTask<Integer> futureTask = new FutureTask<Integer>(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
System.out.println("(预加载线程输出)开始计算...");
Thread.sleep(2000);
System.out.println("(预加载线程输出)计算完成...");
return Integer.MAX_VALUE;
}
});
private final Thread thread = new Thread(futureTask);
public void start() { thread.start();}
public int get() throws ExecutionException, InterruptedException {
return futureTask.get();
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
Demo2 demo2 = new Demo2();
System.out.println("(主线程输出)预加载...");
demo2.start();
Thread.sleep(1000);
System.out.println("(主线程输出)计算结果为(如果没计算出来则等待):");
System.out.println("(主线程输出)计算结果为:" + demo2.get());
}
}
运行结果为: