romworld

Thread 경마 프로그램 본문

JAVA/개념정리

Thread 경마 프로그램

inderrom 2022. 11. 27. 19:00
package kr.or.ddit.basic;

import java.util.Arrays;

/*
	10마리의 말들이 경주하는 경마 프로그램 작성하기
	
	말은 Horse라는 이름의 쓰레드 클래스로 작성하는데 이 클래스는
	말이름(String), 등수(int), 현재위치(int)를 멤버변수로 갖는다.
	그리고 이 클래스는 등수를 오름차순으로 처리할 수 있는 내부 정렬 기준이 있다.
	(Comparable인터페이스 구현)
	
	경기 구간은 1 ~ 50구간으로 되어 있다. (a~z 출력이랑 같은 뜻)
	
	경기 중에는 중간 중간에 각 말들의 위치를 아래 예시와 같이 나타낸다.
	
	예시)
	01번말 : ---->---------------------------
	02번말 : ->-------------------------------
	~~~
	10번말 : --------->-----------------------
	
	경기가 끝나면 등수의 오름차순으로 정렬하여 출력한다.
*/
public class ThreadTest10 {
	
	public static void main(String[] args) {
		Horse[] horses = new Horse[] {
				
			new Horse("01번말"),	
			new Horse("02번말"),	
			new Horse("03번말"),	
			new Horse("04번말"),	
			new Horse("05번말"),	
			new Horse("06번말"),	
			new Horse("07번말"),	
			new Horse("08번말"),	
			new Horse("09번말"),	
			new Horse("10번말")	
		};
		
		GameState gs = new GameState(horses);
		for(Horse h : horses) {
			h.start();		// 말들의 경주 시작
		}
		
		gs.start();		// 말들의 현재 위치 출력
		
		//--------------------------------------------
		// 말들의 경주가 모두 끝날때까지 기다린다
		for(Horse h : horses) {
			try {
				h.join();
			} catch (InterruptedException e) {
				// TODO: handle exception
			}
		}
		
		try {
			gs.join();
		} catch (InterruptedException e) {
			// TODO: handle exception
		}
		//------------------------------------------------
		System.out.println();
		System.out.println("경기 끝...");
		System.out.println();
		
		// 등수의 오름차순으로 정렬한 후 출력하기
		
		// 배열의 데이터들을 정렬하기
		Arrays.sort(horses);
		
		for(Horse h : horses) {
			System.out.println(h);
		}
		
		
		
		
	}
}

class Horse extends Thread implements Comparable<Horse>{
	public static int currentRank = 0; // 말들의 등수를 구하기 위한 변수 선언
	
	private String horseName;   // 말이름
	private int rank;			// 등수
	private int location;		// 현재위치
	
	// 생성자
	public Horse(String horseName) {
		this.horseName = horseName;
		
	}

	public String getHorseName() {
		return horseName;
	}

	public void setHorseName(String horseName) {
		this.horseName = horseName;
	}

	public int getRank() {
		return rank;
	}

	public void setRank(int rank) {
		this.rank = rank;
	}

	public int getLocation() {
		return location;
	}

	public void setLocation(int location) {
		this.location = location;
	}
	
	@Override
	public String toString() {
		return "경주마 " + horseName + "은(는) " + rank + "등 입니다.";
	}

	@Override
	public int compareTo(Horse horse) {
		
		return Integer.compare(this.rank, horse.getRank());
	}
	
	@Override
	public void run() {
		// 쓰레드에서 현재 말이 달리기를 진행한다.
		for(int i= 1; i<=50; i++ ) {
			this.location = i;
			try {
				Thread.sleep((int)(Math.random() * 500));
			} catch (InterruptedException e) {
				// TODO: handle exception
			}
		}
		// 한 마리의 말이 경주가 끝나면 등수를 구해서 저장한다.
		currentRank++;
		this.rank=currentRank;
	}
	
}

/*
 경기 중에는 중간 중간에 각 말들의 위치를 아래 예시와 같이 나타낸다.
	
	예시)
	01번말 : ---->---------------------------
	02번말 : ->-------------------------------
	~~~
	10번말 : --------->-----------------------
 */
 
// 경기 중에 현재 말의 위치를 나타내는 쓰레드
class GameState extends Thread{
	private Horse[] horses;

	// 생성자 - 배열을 인스턴스로 받아서 초기화 시켜주는 것
	public GameState(Horse[] horses) {
		super();
		this.horses = horses;
	}
	
	@Override
	public void run() {
		while(true) {
			// 말들의 경주가 모두 끝났는지 여부 검사
			if(Horse.currentRank==horses.length) {
				break;
			}
			
			// 빈 줄 출력
			for(int i=1; i<=10; i++) {
				System.out.println();
			}
			
			for(int i=0; i<horses.length; i++) {
				System.out.print(horses[i].getHorseName() + " : ");
				
				for(int j=1; j<=50; j++) {
					if(horses[i].getLocation() == j) {	// 말의 현재 위치 찾기
						System.out.print(">");
					}else {
						System.out.print("-");
					}
				}
				System.out.println();	// 줄바꿈
			}
			
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				// TODO: handle exception
			}
			
		}
	}
	
}

'JAVA > 개념정리' 카테고리의 다른 글

JDBC  (0) 2022.11.27
Thread 2  (0) 2022.11.27
Thread  (0) 2022.10.31
Generic  (0) 2022.10.31
enum  (1) 2022.10.31
Comments