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 {

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值