public class Test {
public static void main(String[] args) {
ExecutorService executor = Executors.newSingleThreadExecutor();
FutureTask future = new FutureTask(new Callable() {
public URLConnection call() throws Exception {
// TODO Auto-generated method stub
//真正的任务在这里执行,这里返回类型为string,可以为任意类型的数据
URL realUrl = new URL("http://www.baidu.com");
//打开和url之间的链接
URLConnection connection = realUrl.openConnection();
connection.connect();
return connection;
}
});
executor.execute(future);
try{
URLConnection result = future.get(5000, TimeUnit.MILLISECONDS);
System.out.println(result.getURL());
}catch(InterruptedException e){
future.cancel(true); //取消任务
System.out.print("提前中断");
}catch(ExecutionException e){
future.cancel(true); //取消任务
System.out.print("任务奔溃");
}catch (TimeoutException e) {
// TODO: handle exception
future.cancel(true); //取消任务
System.out.print("超时异常");
}finally {
executor.shutdown();
}
}
}