更新時間: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(); } }
在這個示例中,每匹馬都有一個隨機生成的速度,每次移動一定的步數。每匹馬都有一個起跑線的位置,當它們越過終點線時,會觸發(fā)一個“勝利”的方法,并且在控制臺上輸出獲勝馬匹的信息。
在'Race'類中,'startRace()'方法啟動每個馬匹線程,每個線程都運行一個'Horse'。