案例:模拟龟兔赛跑
赛道:1000米,兔子每秒100米,乌龟每秒50米,兔子跑到900米处开始睡觉(自己把自己挂起),乌龟一直跑,乌龟跑到终点 唤醒兔子,最终乌龟获得比赛胜利,兔子比赛失败
- 兔子类
package com.itguo.anli02;
public class Rabbit extends Thread{
private String name;
public Rabbit(String name) {
//通过super(name)来设置名字
super(name);
}
@Override
public void run() {
for (int i = 0; i <=900; i+=100) {
System.out.println(Thread.currentThread().getName()+"跑了"+(i+100)+"米");
if (i==800){
System.out.println(Thread.currentThread().getName()+"开始睡觉了");
//兔子自己挂起自己
Thread.currentThread().suspend();
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("兔子跑完了全程,比赛失败");
}
}
- 乌龟类
package com.itguo.anli02;
public class Tortoise extends Thread{
private String name;
private Rabbit rabbit;
public Tortoise(String name, Rabbit rabbit) {
super(name);
this.rabbit = rabbit;
}
/**
唤醒兔子的方法
*/
public void hxRabbit(){
rabbit.resume();
System.out.println(this.getName()+"唤醒了"+rabbit.getName());
}
@Override
public void run() {
for (int i = 0; i <= 950; i+=50) {
System.out.println(Thread.currentThread().getName()+"跑了"+(i+50)+"米");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("乌龟跑完了全程,比赛胜利");
hxRabbit();
}
}
- 主函数
package com.itguo.anli02;
public class anli02 {
public static void main(String[] args) {
//创建兔子对象
Rabbit rabbit = new Rabbit("兔子");
//创建乌龟对象
Tortoise tortoise = new Tortoise("乌龟",rabbit);
rabbit.start();
tortoise.start();
}
}