《java并发编程实战》基础构建模块(七)

5.5.2 FutureTask

package com.imeiren.cache;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

class Preloader {
	private final FutureTask<String> future = new FutureTask<String>(
			new Callable<String>() {
				@Override
				public String call() throws Exception {
					// 模拟从数据库或者网络预加载数据
					Thread.sleep(3000);
					return "Java Concurrency in Practice!";
				}
			});

	private final Thread thread = new Thread(future);

	public void start() {
		thread.start();
	}

	public String get() {
		String result = null;
		try {
			result = future.get();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
		return result;
	}
}

public class FutureTaskTester {
	public static void main(String[] args) {
		Preloader preloader = new Preloader();
		preloader.start();
		//模拟主线程去干点其它事情
		try {
			Thread.sleep(4000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println(preloader.get());
	}
}
FutureTask在Executor框架中表示异步任务,此外还可以用来表示一些时间较长的计算,这些计算可以在使用计算结果之前启动。

你可能感兴趣的:(《java并发编程实战》基础构建模块(七))