“탁월함은 기술이 아니다. 태도입니다.”
– 랄프 마스턴
사용자로부터 경주마 개수를 입력받고
입력받은 개수만큼 독립적으로 경주마는 움직인다.
각 경주마는 경기장을 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();
}
}
}
'Java 응용' 카테고리의 다른 글
Java 응용 (9. Echo Server / Client) (0) | 2024.04.12 |
---|---|
Java 응용 (8. 끝말잇기 게임) (0) | 2024.04.11 |
Java 응용 (6. 랜덤한 숫자 맞추기) (0) | 2024.04.08 |
Java 응용 (5. 이메일 검색 서비스) (0) | 2024.03.14 |
Java 응용 (4. 숫자 위치 맞추기) (0) | 2024.03.06 |