Java 응용

Java 응용 (7. Thread를 이용한 경마 게임)

Kw_w 2024. 4. 8. 20:21
“탁월함은 기술이 아니다. 태도입니다.”
– 랄프 마스턴

 

사용자로부터 경주마 개수를 입력받고
입력받은 개수만큼 독립적으로 경주마는 움직인다.

각 경주마는 경기장을 10바퀴 도는데
한번 돌때마다 10m씩 이동한다.
한번 돌때마다 이동한 거리 출력해야하며, 100m가 되었을 때 결승선이 통과된다.

1. 사용자의 입력으로 경주마의 마릿수를 받고
2. 입력 받은 마릿수만큼 스레드를 생성하고
3. 생성된 스레드의 RUN 블럭에 반복분(10번)을 수행

 

Code 1

import java.util.Scanner;

public class HorseRun extends Thread {
    private int horseId;

    public HorseRun(int horseId) {
        this.horseId = horseId;
    }

    public void run() {
        int distance = 0;
        for (int lap = 1; lap <= 10; lap++) {
            distance += 10;
            System.out.println("Horse " + horseId +", Distance: " + distance + "m");

            if (distance >= 100) {
                System.out.println("Horse " + horseId + " 결승선 통과!");
                break;
            }
        }
    }

    public static void main(String[] args) {
        Scanner sc= new Scanner(System.in);
        System.out.print("Enter the number of racehorses: ");
        int Horses = sc.nextInt();

        HorseRun[] horses = new HorseRun[Horses];

        for (int i = 0; i < Horses; i++) {
            horses[i] = new HorseRun(i + 1);
            horses[i].start();
        }
    }
}

 

Code 2

import java.util.Random;
import java.util.Scanner;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Horse extends Thread{
    private String name;
    private int distance;

    public Horse(String name){
        this.name = name;
    }

    @Override
    public void run() {
        while (distance != 100){
            distance += 10;
            System.out.println(name +" 이동거리 : "+distance+"m");
            try {
                Thread.sleep(new Random().nextInt(1000)+1);
            }catch (InterruptedException e){
                throw new RuntimeException(e);
            }
        }
        System.out.println(name + " 결승점 통과!");
    }
}
class Game {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int horseNum = sc.nextInt();

        ExecutorService service = Executors.newFixedThreadPool(horseNum);

        for(int i =0; i<horseNum; i++){
            service.execute(new Horse("[ "+(i+1)+" horse ]"));
//            new Thread(new Horse("[ "+(i+1)+" horse ]")).start();
        }
    }
}