Java编程编写一个龟兔赛跑的多线程程序,单击按键以后龟兔开始赛跑
时间: 2023-05-29 20:01:59 浏览: 185
这是一个简单的龟兔赛跑多线程程序,点击“开始赛跑”按钮后,龟兔开始在轨道上赛跑,其中兔子有80%的概率在每秒钟内走两步,20%的概率休息一秒钟;乌龟每秒钟走一步。程序会在任意一只动物走过终点时停止。
```
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Race extends JFrame implements ActionListener {
private JButton startButton;
private JTextArea raceTrack;
private Rabbit rabbit;
private Turtle turtle;
public static void main(String[] args) {
Race race = new Race();
race.setVisible(true);
}
public Race() {
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setTitle("Race");
setSize(400, 400);
startButton = new JButton("开始赛跑");
startButton.addActionListener(this);
JPanel buttonPanel = new JPanel();
buttonPanel.add(startButton);
raceTrack = new JTextArea();
JScrollPane scrollPane = new JScrollPane(raceTrack);
Container contentPane = getContentPane();
contentPane.setLayout(new BorderLayout());
contentPane.add(buttonPanel, BorderLayout.PAGE_START);
contentPane.add(scrollPane, BorderLayout.CENTER);
}
public void actionPerformed(ActionEvent event) {
if (event.getSource() == startButton) {
startRace();
}
}
public void startRace() {
raceTrack.setText("");
rabbit = new Rabbit();
turtle = new Turtle();
rabbit.start();
turtle.start();
}
private class Rabbit extends Thread {
public void run() {
int distance = 0;
while (distance < 100) {
if (Math.random() < 0.8) {
distance += 2;
} else {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
updateRace(distance, "兔子");
}
finishRace("兔子");
}
}
private class Turtle extends Thread {
public void run() {
int distance = 0;
while (distance < 100) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
distance += 1;
updateRace(distance, "乌龟");
}
finishRace("乌龟");
}
}
private synchronized void updateRace(int distance, String animalName) {
raceTrack.append(animalName + "前进了" + distance + "米。\n");
if (distance >= 100) {
finishRace(animalName);
}
}
private synchronized void finishRace(String winner) {
raceTrack.append("结束!" + winner + "赢了!\n");
if (rabbit != null) {
rabbit.interrupt();
rabbit = null;
}
if (turtle != null) {
turtle.interrupt();
turtle = null;
}
}
}
```
阅读全文