首页 > 代码库 > jdk future

jdk future

package aaa.bbb;


import java.util.concurrent.Callable;

import java.util.concurrent.ExecutionException;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

import java.util.concurrent.FutureTask;

import java.util.concurrent.TimeUnit;

import java.util.concurrent.TimeoutException;



public class Serv {

public static void main(String[] args) {

ExecutorService executorService = Executors.newSingleThreadExecutor();

FutureTask<String> future =new FutureTask<String>(new Callable<String>() {

public String call() throws Exception {

Thread.sleep(20000);

return "aaaaaaaaaaaaaaa";

}

});

executorService.execute( future);

try {

String s = future.get(1000, TimeUnit.MILLISECONDS);

System.out.println(s);

} catch (InterruptedException e) {

e.printStackTrace();

} catch (ExecutionException e) {

e.printStackTrace();

} catch (TimeoutException e) {

future.cancel(true);

e.printStackTrace();

}finally {   

executorService.shutdown();   

}  

}

}


jdk future