고급JAVA 8강 - 쓰레드의 상태

Whatever·2021년 11월 8일
0

고급 JAVA

목록 보기
8/32

컴퓨터와 가위 바위 보를 진행하는 프로그램을 작성하시오.

컴퓨터의 가위 바위 보는 난수를 이용해서 구하고, 사용자의 가위 바위 보는 showInputDialog()메서드를 이용해서 입력 받는다.

입력시간은 5초로 제한하고, 카운트 다운을 한다.
5초 안에 입력이 없으면 게임에 진것으로 처리한 후 끝낸다.

5초 안에 입력이 있으면 승패를 구해서 출력한다.

결과 예시)
1) 5초안에 입력이 완료되었을 때
-- 결 과 --
컴퓨터 : 가위
사용자 : 바위
결 과 : 당신이 이겼습니다.

2) 5초안에 입력을 못했을 경우
-- 결 과 --
시간초과로 당신이 졌습니다.

내 답

public class ThreadTest09 {

public static void main(String[] args) {

	Thread th1 = new Game();
	Thread th2 = new Count();
	
	th1.start();
	th2.start();
}

}

사용자에게 입력받는 클래스
class Game extends Thread{

public static boolean checkInput = false;

@Override
public void run() {
	String answer = JOptionPane.showInputDialog("가위, 바위, 보 중 하나를 입력하세요.");
	checkInput = true;
	//가위, 바위, 보를 int로 변경해서 구하는게 더 쉬울까??
	
	//컴퓨터 가위바위보 값 받기
	String com = make();
	
	//가위바위보 비교해서 결과 도출
	//같은 경우
	if(answer.equals(com)) {
		System.out.println("-- 결 과 --");
		System.out.println("비겼습니다.");
	}
	//컴퓨터가 이기는 경우
	if(answer.equals("가위") && com.equals("바위") ||
		answer.equals("바위") && com.equals("보") ||
		answer.equals("보") && com.equals("가위")) {
		System.out.println("-- 결 과 --");
		System.out.println("당신이 졌습니다.");
	}
	
	//사용자가 이기는 경우
	if(com.equals("가위") && answer.equals("바위") ||
			com.equals("바위") && answer.equals("보") ||
			com.equals("보") && answer.equals("가위")) {
		System.out.println("-- 결 과 --");
			System.out.println("당신이 이겼습니다.");
		}
	System.out.println("컴퓨터 : " + com);
	System.out.println("당신 : " + answer);
	
}

//컴퓨터 가위바위보
private String make() {
	int random = (int)(Math.random() * 3) + 1;
	switch(random) {
	case 1: return "가위";
	case 2:	return "바위";
	case 3: return "보";
	default : return null;
	}
	
}

}

//카운트다운 클래스
class Count extends Thread{

@Override
public void run() {
	System.out.println("카운트다운 시작");
	for(int i = 5; i > 0; i--) {
		if(Game.checkInput) {
			return;
		}
		System.out.println(i);
		
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	if(Game.checkInput) {
		return;
	}
	System.out.println("시간초과로 당신이 졌습니다. ");
	return;
}

}

// 난수를 이용해서 컴퓨터의 가위 바위 보 정하기 -- 선생님답
  String[] data {"가위", "바위", "보"}; //index ==> 0 ~ 2 사이의 값
  int index = (int)(Math.random() * 3);
  String com = data[index];

  //사용자의 가위 바위 보 입력받기
  th1.start //카운트다운 실행
  String man = JOptionPane.ShowInputDialog("가위바위보를 입력하세요");

  //결과 판정하기
  String result = ""; //결과가 저장될 변수 선언
  if(com.equals(man)){
      result = "비겼습니다.";
  }else if(사용자가 이기는 경우){
      result = "당신이 이겼습니다.";
  }else{
      result = "당신이 졌습니다.";
  }

  //결과 출력
  sysout("결과")
  sysout("컴퓨터 : " + com)
  sysout("당신 : " + man)

쓰레드 상태

  //쓰레드 상태의 검사 대상이 되는 쓰레드
class TargetThread2 extends Thread{
    @Override
    public void run() {
        for(long i = 1L; i <= 2000000000000000000L; i++) {}
		
	try {
		Thread.sleep(1500);
	} catch (InterruptedException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
		
	for(long i = 1L; i <= 2000000000000000000L; i++) {}
}

}

class StatePrintThread2 extends Thread{
private TargetThread2 target;

public StatePrintThread2(TargetThread2 target) {
	this.target = target;
}

@Override
public void run() {
	while(true) {
		//쓰레드의 현재 상태값 구하기
		Thread.State state = target.getState();
		System.out.println("현재 상태값 : " + state);
		
		if(state == Thread.State.NEW) {
			target.start();
		}
		
		if(state == Thread.State.TERMINATED) {
			break;
		}
		
		try {
			Thread.sleep(500);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

}

Thread.State => 쓰레드의 현재 상태를 나타내는 enum

yield() 메서드 연습

public class ThreadTest11 {

public static void main(String[] args) {
	YieldTread th1 = new YieldTread("1번 쓰레드");
	YieldTread th2 = new YieldTread("2번 쓰레드");
	
	th1.start();
	th2.start();
	
	try {
		Thread.sleep(1);
	} catch (InterruptedException e) {
		// TODO: handle exception
	}
	
	System.out.println("11111----------------------------11111");
	
	th1.work = false;
	
	try {
		Thread.sleep(1);
	} catch (InterruptedException e) {
		// TODO: handle exception
	}
	
	System.out.println("22222----------------------------22222");
	th1.work = true;
	
	try {
		Thread.sleep(1);
	} catch (InterruptedException e) {
		// TODO: handle exception
	}
	
	System.out.println("33333----------------------------33333");
	
	th1.stop = true;
	th2.stop = true;
}

}

// yield()메서드 연습용 쓰레드
class YieldTread extends Thread{
    public boolean stop = false;
    public boolean work = true;

public YieldTread(String name) {
	super(name); // 쓰레드의 이름 설정하기
}

@Override
public void run() {
	while(!stop) { // stop값이 true이면 반복문 탈출
		if(work) {
			//getName()메서드 ==> 쓰레드 이름(name속성값) 반환
			System.out.println(getName() + " 작업중...");
		}else {
			System.out.println(getName() + " 양보...");
			Thread.yield();
			 
		}
		
	}

}

}

3개의 쓰레드가 각각 알파벳 A-Z까지 출력하는데
출력을 끝낸 순서대로 결과를 나타내는 프로그램 작성하기

public class ThreadTest12 {

public static void main(String[] args) {
	DisplayCharacter[] ths = new DisplayCharacter[] { //배열로 쓰레드 생성
			new DisplayCharacter("홍길동"),
			new DisplayCharacter("이순신"),
			new DisplayCharacter("강감찬")
	};
	
	for(DisplayCharacter dc : ths) { //쓰레드를 돌아가면서 하나씩 실행시킴
		dc.start();
	}
	
	//모든 경기가 끝날 때까지 기다린다.
	for(DisplayCharacter dc : ths) {
		try {
			dc.join(); 
		} catch (InterruptedException e) {
			// TODO: handle exception
		}
	}
	
	System.out.println();
	System.out.println("경기 결과");
	System.out.println("순위 : " + DisplayCharacter.setRank);
}

}

// A ~ Z 까지 출력하는 쓰레드
class DisplayCharacter extends Thread {
public static String setRank = "";
private String name;

// 생성자
public DisplayCharacter(String name) {
	this.name = name;
}

@Override
public void run() {
	for(char ch = 'A'; ch <= 'Z'; ch++) {
		System.out.println(name + "의 출력 문자 : " + ch);
		try {
			// 0~499사이의 난수값으로 일시정지 시킨다.
			Thread.sleep((int)(Math.random() * 500));
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	System.out.println(name + "출력 끝...");
	
	// 출력을 끝낸 순서대로 이름을 배치한다.
	DisplayCharacter.setRank += name + ' ';
}

}

         

0개의 댓글