Callable与Future,FutureTask

callable,future,futureTask基础:[url]http://www.cnblogs.com/dolphin0520/p/3949310.html[/url]
线程池:[url]http://cuisuqiang.iteye.com/blog/2019372[/url]
主类:
callable+future
public class TestFuture {
public static void main(String[] args) {
ExecutorService threadPool = Executors.newCachedThreadPool();
Future<Boolean> uFuture = threadPool.submit(new UpdateCallable(6000));
Future<Boolean> IFuture = threadPool.submit(new InsertCallable(12000));
try {
threadPool.shutdown();//直到线程执行完毕
boolean flag = true;
while(flag){
if(uFuture.get()&&IFuture.get()){
flag = false;
System.out.println("is over!");
}
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}


callable+futureTask
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;


public class testFutureTask {
public static void main(String[] args) {
ExecutorService threadPool = Executors.newCachedThreadPool();
UpdateCallable utask = new UpdateCallable(6000);
InsertCallable itask = new InsertCallable(12000);
FutureTask<Boolean> UfutureTask = new FutureTask<Boolean>(utask);
FutureTask<Boolean> IfutureTask = new FutureTask<Boolean>(itask);
threadPool.submit(UfutureTask);
threadPool.submit(IfutureTask);
try {
threadPool.shutdown();//直到线程执行完毕
boolean flag = true;
while(flag){
if(UfutureTask.get()&&IfutureTask.get()){
flag = false;
System.out.println("is over!");
}
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}

Callable:
import java.util.concurrent.Callable;

public class InsertCallable implements Callable<Boolean> {
private Integer time = 3000;

public InsertCallable(Integer time) {
super();
this.time = time;
}

public Boolean call() throws Exception {
System.out.println("InsertCallable sleep time:" + time);
Thread.sleep(time);
System.out.println("InsertCallable up");
return true;
}
}
import java.util.concurrent.Callable;

public class UpdateCallable implements Callable<Boolean> {
private Integer time = 3000;

public UpdateCallable(Integer time) {
super();
this.time = time;
}

public Boolean call() throws Exception {
System.out.println("UpdateCallable sleep time:" + time);
Thread.sleep(time);
System.out.println("UpdateCallable up");
return true;
}
}

测试结果:
UpdateCallable sleep time:6000
InsertCallable sleep time:12000
UpdateCallable up
InsertCallable up
is over!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值