package callable;
import java.util.concurrent.*;
/**
-
龟兔赛跑例子
-
Created by lxq on 2019/7/13.
-
通过Callable接口实现多线程
-
优点:可以获取返回值
-
缺点:繁琐
-
思路:
-
1、创建Callable实现类 + 重写call
-
2、借助执行调度任务 ExecutorService 获取Future对象
-
ExecutorService ser = Executors.newfixedThreadPool(2);
-
Future result = ser.submit(实现类对象);
-
3、获取值result.get();
-
4、停止服务,ser.shutdownNow();
*/
public class Call {public static void main(String[] args) throws ExecutionException, InterruptedException {
//创建线程
ExecutorService ser = Executors.newFixedThreadPool(2);
Race tortoise = new Race(“乌龟”,1000);
Race rabbit = new Race(“兔子”,500);
//获取值
Future result1 = ser.submit(tortoise);
Future result2 = ser.submit(rabbit);Thread.sleep(2000);//跑2秒 tortoise.setFlag(false);//停止线程体循环 rabbit.setFlag(false); int num1 = result1.get(); int num2 = result2.get(); System.out.println("乌龟跑了--》"+num1+"步"); System.out.println("兔子跑了--》"+num2+"步"); //停止服务 ser.shutdownNow();
}
}
class Race implements Callable{
private String name;//名称
private long time; //延时时间
private boolean flag = true;
private int step =0;//步
public Race(String name){
super();
this.name = name;
}
public Race(String name,long time){
super();
this.name = name;
this.time = time;
}
@Override
public Integer call() throws Exception {
while (flag){
Thread.sleep(time);//延时
step++;
}
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 boolean isFlag() {
return flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
public int getStep() {
return step;
}
public void setStep(int step) {
this.step = step;
}
}