import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class FutureTest {
private static ExecutorService executor = Executors.newCachedThreadPool();
private static final long FutureTimeOut = 1000; //线程最大等待时间s
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
final Map<String,String> map=new HashMap<String, String>();
Future future1 = null;
Future future2 = null;
try {
future1 = executor.submit(new Runnable(){
@Override
public void run() {
map.put("1", chengeValue("1"));
}
});
future2 = executor.submit(new Runnable(){
@Override
public void run() {
map.put("2", chengeValue("2"));
}
});
future1.get(FutureTimeOut , TimeUnit.SECONDS );
future2.get(FutureTimeOut , TimeUnit.SECONDS );
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TimeoutException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(map.toString());
}
public static String chengeValue(String value){
if("1".equals(value)){
return "this is first";
}else{
return "this is last";
}
}
}
?
|