原文:https://blog.csdn.net/qq_34996727/article/details/80416277
修改了原文中: Thread 的方法 stop(),改为用标志位来终止线程
package thread_rabbit_tortoise;
public abstract class Animal extends Thread {
volatile boolean stop = false;
public int length = 30;// 比赛长度
public abstract void runing();
@Override
public void run() {
while (!stop&&length>0) {
runing();
}
}
public void terminate() {
stop = true;
}
// 在需要回调数据的地方(两个子类需要),声明一个接口
public static interface Calltoback {
public void win();
}
// 2.创建接口对象
public Calltoback calltoback;
}
package thread_rabbit_tortoise;
public class Rabbit extends Animal {
public Rabbit() {
setName("兔子");
}
@Override
public void runing() {
//兔子速度
int dis = 5;
length -= dis;
System.out.println("兔子跑了" + dis + "米,距离终点还有" + length + "米");
if (length <= 0) {
length = 0;
System.out.println("兔子获得了胜利");
// 给回调对象赋值,让乌龟不要再跑了
if (calltoback != null) {
calltoback.win();
}
}
try {
if ((2000 - length) % 20 == 0) { // 每20米休息一次,休息时间是1秒
sleep(1000);
} else { //没0.1秒跑5米
sleep(100);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
package thread_rabbit_tortoise;
public class Tortoise extends Animal {
public Tortoise() {
setName("乌龟");// Thread的方法,给线程赋值名字
}
// 重写running方法,编写乌龟的奔跑操作
@Override
public void runing() {
// 乌龟速度
int dis = 2;
length -= dis;
System.out.println("乌龟跑了" + dis + "米,距离终点还有" + length + "米");
if (length <= 0) {
length = 0;
System.out.println("乌龟获得了胜利");
// 让兔子不要在跑了
if (calltoback != null) {
calltoback.win();
}
}
try {
sleep(100); //没0.1秒跑2米
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
package thread_rabbit_tortoise;
import thread_rabbit_tortoise.Animal.Calltoback;
public class LetOneStop implements Calltoback {
// 动物对象
Animal an;
// 获取动物对象,可以传入兔子或乌龟的实例
public LetOneStop(Animal an) {
this.an = an;
}
// 让动物的线程停止
@Override
public void win() {
// 线程停止
an.terminate();
}
}
package thread_rabbit_tortoise;
public class MainClass {
public static void main(String[] args) {
Tortoise tortoise = new Tortoise();
Rabbit rabbit = new Rabbit();
LetOneStop letOneStop1 = new LetOneStop(tortoise);
rabbit.calltoback = letOneStop1;
LetOneStop letOneStop2 = new LetOneStop(rabbit);
tortoise.calltoback = letOneStop2;
tortoise.start();
rabbit.start();
}
}