第一天的感受。

 今天來到我們程序員自己的社區,感到很親切!

 

太棒了。

 

用線程方法實現龜兔賽跑,龜和兔可以用兩個點表示,看他們哪個點先到終點:

 

 

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.");
}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章