解决流程
线程龟兔赛跑也就是说有两个线程在同时跑,一个兔子 一个乌龟。
new Thread(g,"兔子").start();开启兔子线程
new Thread(g,"乌龟").start();开启乌龟线程
重写的run()方法里面我们记录兔子和乌龟的步伐
定义一个游戏方法gameOver(),通过对步伐进行判断,判断出谁是赢家,规定达到100步游戏结束,gameOver()方法是boolean类型的,返回值是true或false,在run()方法里面通过if语句来break跳出循环。
Thread.currentThread().getName(),Thread里面有currentThread()方法可以获取线程的名字。
游戏函数
public boolean gameOver(int step){//游戏函数
if (winner!=null){//如果赢家不为空,返回真,跳出循环
return true;
}if (step>=100){//如果步数达到100返回真,跳出循环
winner=Thread.currentThread().getName();
System.out.println("获得胜利的是"+winner);
return true;
}else {
return false;
}
}
run()函数
@Override
public void run() {
for (int i = 0; i <= 100; i++) {
// if (Thread.currentThread().getName().equals("兔子")){//如果兔子跑的快,可以让其睡觉
// try {
// Thread.sleep(10);//可以让其睡觉
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }
boolean flag=gameOver(i);//通过游戏函数返回的值来判断是否跳出循环
if (flag){
break;
}
System.out.println(Thread.currentThread().getName()+"跑了"+i+"步");
}
完整代码
package ThreadStudy.TestThread;
public class GuiTuSaiPao implements Runnable {
private static String winner;
@Override
public void run() {
for (int i = 0; i <= 100; i++) {
// if (Thread.currentThread().getName().equals("兔子")){
// try {
// Thread.sleep(10);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }
boolean flag=gameOver(i);
if (flag){
break;
}
System.out.println(Thread.currentThread().getName()+"跑了"+i+"步");
}
}
public boolean gameOver(int step){
if (winner!=null){
return true;
}if (step>=100){
winner=Thread.currentThread().getName();
System.out.println("获得胜利的是"+winner);
return true;
}else {
return false;
}
}
public static void main(String[] args) {
GuiTuSaiPao g = new GuiTuSaiPao();
new Thread(g,"兔子").start();
new Thread(g,"乌龟").start();
}
}