今天来到我们程序员自己的社区,感到很亲切!
太棒了。
用线程方法实现龟兔赛跑,龟和兔可以用两个点表示,看他们哪个点先到终点:
public class Game extends Thread {
int distance = 46;
boolean run = true;
Rabbit rabbit = new Rabbit(this);
Turtle turtle = new Turtle(this);
@Override
public void run() {
while(run) {
if(!rabbit.end)
rabbit.run();
if(!turtle.end)
turtle.run();
check();
}
}
public void check() {
if(rabbit.end && turtle.end) {
run = false;
}
}
public static void main(String[] args) {
Game game = new Game();
game.start();
}
}
abstract class Racer {
int space;
Game game;
boolean end;
public Racer(Game game) {
this.game = game;
}
public void run() {System.out.println("run:space=" + space);
if(!isRest()) {
space += getSpeed();
if(check()) {
end();
end = true;
}
}
}
public boolean check() {
return space >= game.distance;
}
public abstract int getSpeed();
public abstract boolean isRest();
public abstract void end();
}
class Rabbit extends Racer {
int sleepTime;
public Rabbit(Game game) {
super(game);
}
public boolean isOneUpVery() {
return (space - game.turtle.space) > 3;
}
public boolean isRest() {System.out.println("rabbit.isRest():isOneUpVery=" + isOneUpVery() + " sleepTime=" + sleepTime);
if(sleepTime == 0) {
if(isOneUpVery()) {
sleepTime = 8;
return true;
}
return false;
} else {
--sleepTime;
}
return true;
}
public int getSpeed() {
return 5;
}
public void end() {
System.out.println("Rabbit is end.");
}
}
class Turtle extends Racer {
public Turtle(Game game) {
super(game);
}
public boolean isRest() {
return false;
}
public int getSpeed() {
return 1;
}
public void end() {
System.out.println("turtle is end.");
}
}