競馬

3444 ワード

10마리의 말들이 경주하는 프로그램을 작성하시오.

말은 Horse라는 이름의 쓰레드 클래스로 작성하는데
이 클래스는 말이름(String), 등수(int), 현재위치(int)를 
멤버변수로 갖는다. 그리고 이 클래스에는 등수를 오름차순으로
정렬할 수 있는 내부 정렬 기준이 있다. (Comparable 인터페이스 구현)

경기 구간은 1 ~ 50구간으로 되어 있다.

경기가 끝나면 등수 순으로 출력한다.

경기 중에는 중간 중간에 각 말들의 위치를 아래와 같이 나타내 준다.
예)
말이름01 : --->-----------------------------------
말이름02 : ------->-------------------------------
...
말이름10 : ----->---------------------------------
package kr.or.didt.basic;



import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ThreadTest13 {

	public static void main(String[] args) {
		
		List<Horse> ths = new ArrayList<>();//정렬을 해줘야 해서 list로 넣어줌
		ths.add(new Horse("1번말"));
		ths.add(new Horse("2번말"));
		ths.add(new Horse("3번말"));
		ths.add(new Horse("4번말"));
		ths.add(new Horse("5번말"));
		ths.add(new Horse("6번말"));
		ths.add(new Horse("7번말"));
		ths.add(new Horse("8번말"));
		ths.add(new Horse("9번말"));
		ths.add(new Horse("10번말"));
		
		for (Horse hs : ths) { //ths를 hs에 넣고 시작
			hs.start();
		}
		
		while(true){//현재 달리고 있는 위치
			for(int i=0; i<ths.size(); i++){//말의 개수만큼
				System.out.print(ths.get(i).name+" : ");
				for(int j=1; j<=50; j++){
					if(ths.get(i).place == j){//i번째 위치가 j와 같으면 
						System.out.print(">");//>로 변환
						continue;//하고 첫번째 for 문으로 올라가서
					}
					System.out.print("-");//-를 출력?
				}
				System.out.println();
			}
			try {
				Thread.sleep(500);//0.5초의 시간 딜레이
			} catch (InterruptedException e) {
			}
			
			int exitCnt = 0;//스레드 갯수
			for(int i=0; i<ths.size(); i++){
				if(ths.get(i).getState() == Thread.State.TERMINATED) {//스레드의 상태가 종료되었을때
					exitCnt++;//스레드의 갯수를 증가시킴
				}
			}
			if(exitCnt==10) {//10번말이 모두 끝났을때는 끝남
				break;
			}
			System.out.println("\n=========================================================\n");
			//끝나지 않았으면 출력
		}
		
		
		System.out.println();
		Collections.sort(ths);//정렬한것
		System.out.println("===경기결과===");
		for(Horse h: ths){//리스트를 h에 넣고
			System.out.println(h);//h출력
		}
	}

}

class Horse extends Thread implements Comparable<Horse>{
	public static int setRank = 1;//static(정적) 공통으로 갖는 변수(변할 수 있는것)
	public String name;
	public int rank;//인스턴스변수 
	public int place = 1;

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

	@Override
	public void run() {
		for (int i = 0; i < 50; i++) {
			//System.out.println(name + "의 위치 : " + place);
			try {
				Thread.sleep((int) (Math.random() * 500));
				//0~0.5초까지 칸이 랜덤으로 움직임
			} catch (InterruptedException e) {
			
			}
			if(place<50) {//장소가 50까지 가야댐 즉, 50보다 작을때 
				place++;//증가
			}
		}
		System.out.println(name + "경기 완료");
		rank = setRank++;//1등한 다음에 등수에 넣어줌
		System.out.println("등수는 "+rank);//??????????왜,,,,,
	}

	@Override
	public int compareTo(Horse h) {
		return Integer.compare(rank, h.rank);//비교해서 정렬
	}

	@Override
	public String toString() {
		return name + " : " + rank + "등 ";

	
	}	
	
}