概述
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!
最后
以上就是瘦瘦巨人为你收集整理的Callable与Future,FutureTask的全部内容,希望文章能够帮你解决Callable与Future,FutureTask所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复