callable,future,futureTask基础:http://www.cnb
logs.com/dolphin0520/p/3949310.html
线程池:http://cuisuqiang.iteye.com/blog/2019372
主类:
callable+future
class="java" name="code">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!