通过Callable实现多线程
优点:可以获取返回值,可以抛出异常(最突出的两个优点)
Callable 和 Future接口
Callable接口是类似于Runnable的接口,实现Callable接口的类和实现Runnable接口的类都是可被其他线程执行的任务。
Callable和Runnable有几点不同:
(1)Callable规定的方法是call(),Runnable规定的方法是run()
(2)call()方法可抛出异常,而run()方法是不可以抛出异常的
(3)Callable的任务执行后可返回值,运行Callable任务可拿到一个Future对象,而Runnable的任务是不能返回值的。
Future表示异步计算的结果,它提供了检查计算是否完成的方法,以等待计算的完成,并检索计算的结果,通过Future对象可了解任务执行情况,可取消任务的执行,还可获取任务的执行结果。
缺点:繁琐
思路:
(1)创建Callable对象+重写call()方法
(2)借助执行调度服务ExecutorService获取Future对象
package First.Test;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
//通过Callable接口模拟一个龟兔赛跑的例子
public class Call {
public static void main(String[] args) {
ExecutorService es = Executors.newFixedThreadPool(2); //开启两个线程
Race tortoise = new Race("tortoise",1000); //每走一步需要1000毫秒
Race rabbit = new Race("rabbit",500); //每走一步需要500毫秒
Future<Integer> f1 = es.submit(tortoise); //自动在一个线程上执行
Future<Integer> f2 = es.submit(rabbit); //自动在一个线程上执行
try {
Thread.sleep(1000 * 3);//3秒之后
tortoise.setFlag(false);
rabbit.setFlag(false);
System.out.println("tortoise move all step : " + f1.get());
System.out.println("rabbit move all step : " + f2.get());
es.shutdown(); //关闭调度器,这一步尤为重要,不关会一直耗损内存
}
catch (InterruptedException e) {
e.printStackTrace();
}
catch (ExecutionException e) {
e.printStackTrace();
}
}
}
class Race implements Callable<Integer>{
private String name; //参赛者名称
private long time; //参赛者每走一步需要花的时间
private int step; //参赛者总共走了多少步
private boolean flag = true; //比较时间是否结束 默认为未结束
public Race(){}
public Race(String name, long time){
this.name = name;
this.time = time;
}
@Override
public Integer call() throws Exception {
while(flag){
Thread.sleep(time); //模拟参赛者走一步需要花的时长
step++; //比赛时间尚未结束,步数加1
}
return step; //一共走了多少步
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getTime() {
return time;
}
public void setTime(long time) {
this.time = time;
}
public int getStep() {
return step;
}
public void setStep(int step) {
this.step = step;
}
public boolean isFlag() {
return flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
}
运行结果:
tortoise move all step : 3
rabbit move all step : 6