FutureTask实例

package com.zhoubo.concurrent.future;

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

/**
 * Preloader creates a FutureTask that describes the task of loading product information from a database 
 * and a thread in which the computation will be performed. 
 * When the program later needs the ProductInfo, it can call get, which returns the loaded data if it is ready, 
 * or waits for the load to complete if not.
 * @author Administrator
 *
 */
public class Preloader {
	//FutureTask implements the Runnable and Future Task
	private final FutureTask<ProductInfo> future = new FutureTask<ProductInfo>(
			new Callable<ProductInfo>() {
				public ProductInfo call() throws DataLoadException {
					return loadProductInfo();
				}
			});
	private final Thread thread = new Thread(future);

	/**
	 * It provides a start method to start the thread, 
	 * since it is inadvisable to start a thread from a constructor or static initializer
	 */
	public void start() {
		thread.start();
	}
	
	public ProductInfo loadProductInfo(){
		try{
			//使得加载数据延迟,让等待get的现象变得明显
			Thread.currentThread().sleep(2000);
		}catch (Exception e) {
			e.printStackTrace();
		}
		//int k=3/0;//make an exception
		return new ProductInfo("happy every day");
	}

	public ProductInfo get() throws DataLoadException, InterruptedException {
		try {
//			future.cancel(true);
			return future.get();
		} catch (ExecutionException e) {
			//异常处理
			Throwable cause = e.getCause();
			if (cause instanceof DataLoadException)
				throw (DataLoadException) cause;
			else
				throw launderThrowable(cause);
		}
	}
	
	public static RuntimeException launderThrowable(Throwable t) {
	    if (t instanceof RuntimeException)
	        return (RuntimeException) t;
	    else if (t instanceof Error)
	        throw (Error) t;
	    else
	        throw new IllegalStateException("Not unchecked", t);
	}
	
	public static void main(String ...args){
		Preloader loader = new Preloader();
		loader.start();
		try{
			System.out.println(loader.get());
		}catch (Exception e) {
			e.printStackTrace();
		}
	}

}

class ProductInfo {
	private String productName;
	
	public ProductInfo() {
		// TODO Auto-generated constructor stub
	}
	
	public ProductInfo(String productName) {
		this.productName = productName;
	}
	
	@Override
	public String toString() {
		// TODO Auto-generated method stub
		return productName;
	}

}

class DataLoadException extends Exception {

}

你可能感兴趣的:(java,thread)