public static void main(String[] args) {
String failReason = null;
Future<Object> f=new FutureTask(new Callable<Object>() {
@Override
public Object call() throws Exception {
// TODO Auto-generated method stub
Thread.sleep(1000*60);
return null;
}
});
new Thread(f).start();
try {
f.get(5l, TimeUnit.SECONDS);
} catch (InterruptedException e) {
failReason = "执行线程在等待计算结果时被中断!";
} catch (ExecutionException e) {
failReason = "执行线程等待计算结果,但计算抛出异常!";
} catch (TimeoutException e) {
failReason = "执行线程等待计算结果超时,因此中断任务线程!";
}finally{
System.out.println(failReason);
}
}
public static void main(String[] args) {
Timer timer=new Timer();//实例化Timer类
//安排在指定延迟后执行指定的任务。
timer.schedule(new TimerTask(){
public void run(){
System.out.println("out");
this.cancel();
}
},500);//五百毫秒
}