更新時(shí)間:2023-02-20 來源:黑馬程序員 瀏覽量:
下面是一個(gè)基于Java多線程的賽馬游戲示例,該示例中有5匹賽馬,每匹賽馬都是一個(gè)線程。每匹賽馬都有一個(gè)速度和一個(gè)起跑線的位置,他們將在屏幕上移動(dòng),直到達(dá)到終點(diǎn)線。
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(); } }
在這個(gè)示例中,每匹馬都有一個(gè)隨機(jī)生成的速度,每次移動(dòng)一定的步數(shù)。每匹馬都有一個(gè)起跑線的位置,當(dāng)它們?cè)竭^終點(diǎn)線時(shí),會(huì)觸發(fā)一個(gè)“勝利”的方法,并且在控制臺(tái)上輸出獲勝馬匹的信息。
在'Race'類中,'startRace()'方法啟動(dòng)每個(gè)馬匹線程,每個(gè)線程都運(yùn)行一個(gè)'Horse'。