编写Java程序一个龟兔赛跑的多线程程序,单击按键以后龟兔开始赛跑
时间: 2024-03-23 15:42:52 浏览: 74
一个用Java语言编写的龟兔赛跑的程序
好的,我可以帮你编写这个程序。这里是一个基本的Java多线程程序,用于模拟龟兔赛跑:
```
public class TurtleRabbitRace extends Thread {
private static boolean finished = false;
private static String winner = "";
public void run() {
if (Thread.currentThread().getName().equals("turtle")) {
for (int i = 1; i <= 100; i++) {
if (finished) return;
System.out.println("乌龟跑了" + i + "步");
if (i == 100) {
finished = true;
winner = "乌龟";
System.out.println("乌龟赢了!");
}
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} else if (Thread.currentThread().getName().equals("rabbit")) {
for (int i = 1; i <= 100; i++) {
if (finished) return;
System.out.println("兔子跑了" + i + "步");
if (i % 20 == 0) {
System.out.println("兔子睡觉中...");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (i == 100) {
finished = true;
winner = "兔子";
System.out.println("兔子赢了!");
}
}
}
}
public static void main(String[] args) {
Thread turtle = new TurtleRabbitRace();
Thread rabbit = new TurtleRabbitRace();
turtle.setName("turtle");
rabbit.setName("rabbit");
turtle.start();
rabbit.start();
}
}
```
这个程序创建了两个线程,一个是乌龟,一个是兔子。每个线程都会循环100次,模拟赛跑的过程。在循环中,如果其中一个线程已经跑完了比赛,则程序会将 `finished` 设置为 `true`,并设置 `winner` 变量为该线程的名称。最后,程序会输出哪个线程赢得了比赛。
你可以通过单击按键来启动这个程序,例如:
```
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("按任意键开始赛跑...");
scanner.nextLine();
Thread turtle = new TurtleRabbitRace();
Thread rabbit = new TurtleRabbitRace();
turtle.setName("turtle");
rabbit.setName("rabbit");
turtle.start();
rabbit.start();
}
```
这样,当用户按下任意键时,程序就会开始赛跑。
阅读全文