packagecom.demo.test4;importjava.util.ArrayList;importjava.util.List;importjava.util.concurrent.Callable;importjava.util.concurrent.CancellationException;importjava.util.concurrent.ExecutionException;importjava.util.concurrent.ExecutorService;importjava.util.concurrent.Executors;importjava.util.concurrent.Future;importjava.util.concurrent.TimeUnit;/***@authorQQ: 1236897 如果超过限制时间则取消超时线程
**/
public classInvokeDemo {/***@paramargs*/
public static voidmain(String[] args) {//TODO Auto-generated method stub
ExecutorService exec =Executors.newCachedThreadPool();
List searchTasks = new ArrayList();
SearchTask st= null;for (int i = 0; i < 10; i++) {
st= new SearchTask(i, 200);//指定2001 毫米为最大执行时间
if (i == 5)
st= new SearchTask(i, 2001);//指定2001 毫米为最大执行时间
searchTasks.add(st);
}try{//要求认为在2000毫秒内返回结果,否则取消执行。
List>> futures =exec.invokeAll(searchTasks,2000, TimeUnit.MILLISECONDS);//invokeAll//第一个参数是任务列表;第二个参数是过期时间;第三个是过期时间单位
int count = 0;for (Future>future : futures) {try{
List students =future.get();for(Person student : students) {
System.out.println(student.toString());
}
}catch(CancellationException e) {
System.out.println("cancel");
future.cancel(true);
}
System.out.println("-----------------------" +count+ "--------------------");
count++;
}
exec.shutdown();
}catch(InterruptedException e) {
e.printStackTrace();
Thread.interrupted();
}catch(ExecutionException e) {
e.printStackTrace();
}
}
}/*** @filename: SearchTask
* @description: 查询任务
*@authorlida
* @date 2013-4-1 下午3:02:29*/
class SearchTask implements Callable>{public final intclassID;public longsleepTime;/***
* Title:
*
*
* Description:
*
*
*@paramclassID
* 班级编号
*@paramsleepTime
* 模拟操作所用的时间数(毫秒)*/SearchTask(int classID, longsleepTime) {this.classID =classID;this.sleepTime =sleepTime;
}
@Overridepublic List call() throwsException {//模拟操作所用的时间数(毫秒)
Thread.sleep(sleepTime);
List stuList = new ArrayList();
Person p= new Person(1, "name", 2);
Person p2= new Person(2, "name", 3);
stuList.add(p);
stuList.add(p2);returnstuList;
}
}classPerson {private intid;privateString name;private intclassID;public Person(int id, String name, intclassID) {this.id =id;this.name =name;this.classID =classID;
}publicString toString() {return Person.class.getName() + "(id:" + this.id + ",name:" + this.name+ ")";
}
}