更新时间:2023-02-20 来源:黑马程序员 浏览量:
下面是一个基于Java多线程的赛马游戏示例,该示例中有5匹赛马,每匹赛马都是一个线程。每匹赛马都有一个速度和一个起跑线的位置,他们将在屏幕上移动,直到达到终点线。
import java.util.Random; public class Horse implements Runnable { private static int counter = 0; private final int id = counter++; private int strides = 0; private static Random rand = new Random(); private static final int FINISH_LINE = 75; private Race race; public Horse(Race race) { this.race = race; } public synchronized int getStrides() { return strides; } @Override public void run() { try { while(!Thread.interrupted()) { synchronized(this) { strides += rand.nextInt(3); } Thread.sleep(200); race.printHorses(); if(strides >= FINISH_LINE) { race.win(this); return; } } } catch(InterruptedException e) { System.out.println("Horse " + id + " interrupted"); } } @Override public String toString() { return "Horse " + id; } } public class Race { private Horse[] horses; private int numHorses; private static final int FINISH_LINE = 75; private volatile Horse winner; public Race(int numHorses) { this.numHorses = numHorses; horses = new Horse[numHorses]; for(int i = 0; i < numHorses; i++) { horses[i] = new Horse(this); } } public void startRace() { System.out.println("Starting the race..."); for(Horse horse : horses) { new Thread(horse).start(); } } public void win(Horse horse) { synchronized(this) { if(winner == null) { winner = horse; System.out.println("Winner: " + winner); } } } public void printHorses() { for(int i = 0; i < 10; i++) { System.out.println(); } for(int i = 0; i < numHorses; i++) { System.out.print(horses[i] + ": "); for(int j = 0; j < horses[i].getStrides(); j++) { System.out.print("*"); } System.out.println(); } try { Thread.sleep(15); } catch(InterruptedException e) { System.out.println("Interrupted while printing horses"); } } } public class RacingGame { public static void main(String[] args) { Race race = new Race(5); race.startRace(); } }
在这个示例中,每匹马都有一个随机生成的速度,每次移动一定的步数。每匹马都有一个起跑线的位置,当它们越过终点线时,会触发一个“胜利”的方法,并且在控制台上输出获胜马匹的信息。
在'Race'类中,'startRace()'方法启动每个马匹线程,每个线程都运行一个'Horse'。