java invokeall_Java_InvokeAll_又返回值_多个线程同时执行,取消超时线程

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+ ")";

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值