package com.demo.test3;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
/**
* @author QQ: 1236897
*
*/
//有返回值线程
//提前加载
public class FutureTaskTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
long start = System.currentTimeMillis();
PreLoad preLoad = new PreLoad();
preLoad.start();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ProctInfo proctInfo = null;
try {
proctInfo = preLoad.get();
} catch (DataLoadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(proctInfo.getId());
long end = System.currentTimeMillis();
System.out.println("Time - " + (end - start));
}
}
class PreLoad {
private final FutureTask<ProctInfo> future = new FutureTask<ProctInfo>(
new Callable<ProctInfo>() {
@Override
public ProctInfo call() throws Exception {
// TODO Auto-generated method stub
Thread.sleep(6000);
return new ProctInfo();
}
});
private final Thread thread = new Thread(future);
public void start() {
thread.start();
}
public ProctInfo get() throws DataLoadException, InterruptedException {
try {
return future.get();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
Throwable cause = e.getCause();
if (cause instanceof DataLoadException) {
throw (DataLoadException) cause;
} else {
throw launchThrowable(e);
}
}
}
public static RuntimeException launchThrowable(Throwable t){
if(t instanceof RuntimeException){
return (RuntimeException)t;
}else if(t instanceof Error){
throw (Error) t;
}else{
throw new IllegalStateException("Uncheck exception");
}
}
}
class ProctInfo {
private String id = "111";
/**
* @return the id
*/
public String getId() {
return id;
}
}