/**
* Java线程:多线程查询(改进)
*
* @author zaixing 2012-02-28 00:00:00
*/
public class Test3 {
public static boolean hit = false;
public static ExecutorService threadPool;
public static void main(String[] args) throws InterruptedException {
ExecutorService threadPool = Executors.newFixedThreadPool(5);
Callable<String> m1 = new MyCallable1("A");
Callable<String> m2 = new MyCallable1("B");
Callable<String> m3 = new MyCallable1("C");
Callable<String> m4 = new MyCallable1("D");
Callable<String> m5 = new MyCallable1("E");
Collection<Callable<String>> callableList = new ArrayList<Callable<String>>();
callableList.add(m1);
callableList.add(m2);
callableList.add(m3);
callableList.add(m4);
callableList.add(m5);
boolean flag = false;
try {
String f1 = threadPool.invokeAny(callableList,1,TimeUnit.MILLISECONDS);
System.out.println(f1);
System.out.println("****************");
return;
} catch (Exception e) {
System.out.println("Time out");
threadPool.shutdownNow();
flag = true;
}finally{
if(false == flag){
threadPool.shutdownNow();
}
}
}
}
/**
* 查询任务
*/
class MyCallable1 implements Callable<String>{
private String oid;
MyCallable1(String oid) {
this.oid = oid;
}
@Override
public String call() throws Exception {
for(int i = 0; i < 100000; i++);
return oid+"任务返回的内容";
}
}
注意:“System.out.println(f1);”在“String f1 = threadPool.invokeAny(callableList,1,TimeUnit.MILLISECONDS);”执行完之前是不会执行的。