고급자바

단일, 멀티 Thread-22.03.30

AIN99 2022. 3. 30. 13:37
728x90
import javax.swing.JOptionPane;

public class T05_ThreadTest {
/**
 * 단일 스레드에서의 사용자 입력 처리
 */
	public static void main(String[] args) {
		
		String str=JOptionPane.showInputDialog("아무거나 입력하세요.");
		System.out.println("입력한 값은 "+str+"입니다.");
		
		for(int i=10; i>=1; i--) {
			System.out.println(i);
			
			
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

}


멀티스레드 사용

import javax.swing.JOptionPane;

public class T06_ThreadTest {

	public static void main(String[] args) {
		
		Thread th1=new DataInput();
		Thread th2=new CountDown();
		
		th1.start();
		th2.start();
	}

}
class DataInput extends Thread{
	@Override
	public void run() {

		String str=JOptionPane.showInputDialog("아무거나 입력하세요.");
		System.out.println("입력한 값은 "+str+"입니다.");
	}
}
class CountDown extends Thread{
	@Override
	public void run() {
		for(int i=10; i>=1; i--) {
			System.out.println(i);
			
			
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		//10초가 경과되었는데도 입력이 없으면 프로그램을 종료한다.
		System.out.println("10초가 지났습니다. 프로그램을 종료합니다.");
		System.exit(0);  //프로그램을 종료시키는 명령
		
	}
}


+ 수정 체크하기 추가

import javax.swing.JOptionPane;

public class T06_ThreadTest {
	public static boolean inputChk=false; 

	public static void main(String[] args) {
		
		Thread th1=new DataInput();
		Thread th2=new CountDown();
		
		th1.start();
		th2.start();
	}
}
class DataInput extends Thread{
	@Override
	public void run() {

		String str=JOptionPane.showInputDialog("아무거나 입력하세요.");
		 //입력이 완료되면  true로 바꿔준다.
		T06_ThreadTest.inputChk=true;
		System.out.println("입력한 값은 "+str+"입니다.");
	}
}
class CountDown extends Thread{
	@Override
	public void run() {
		for(int i=10; i>=1; i--) {
			System.out.println(i);
			//입력이 완료 되었는지 여부를 검사하고 입력이 완료되면  run()을 종료시킨다. 즉 현재 스레드를 종료 시킨다.
			if(T06_ThreadTest.inputChk==true) {
				return; //리턴을 통해 빠져나온다. run() 메서드 종료 가장 가까운 메서드를 빠져나감, 단지 이 루프만 빠져나가고 싶고 for문 밖에 있는걸 실행하고 싶으면 break
			}
			
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		//10초가 경과되었는데도 입력이 없으면 프로그램을 종료한다.
		System.out.println("10초가 지났습니다. 프로그램을 종료합니다.");
		System.exit(0);  //프로그램을 종료시키는 명령
		
	}
}
더보기

if(T06_ThreadTest.inputChk==true) {
return;

리턴을 통해 빠져나온다. run() 메서드 종료 가장 가까운 메서드를 빠져나감,

단지 이 루프만 빠져나가고 싶고 for문 밖에 있는걸 실행하고 싶으면 break
}


System.exit(0);  //프로그램을 종료시키는 명령

얘를 주석처리 하게되면 시스템이 죽지 않는다. 그래서 강제 종료 시켜줘야 한다.


가위바위보 게임 예제

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

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

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

5초안에 입력이 완료되면 승패를 출력한다.

결과예시)
=== 결 과 ===
컴퓨터 : 가위
당  신 : 바위
결  과 : 당신이 이겼습니다.

import javax.swing.JOptionPane;

public class T07_ThreadGame {
	public static boolean inputCheck = false;

	public static void main(String[] args) {
		GameTimer gt = new GameTimer();

		// 난수를 이용하여 컴퓨터의 가위 바위 보를 정한다.
		String[] data = {"가위", "바위", "보"};
		int index = (int)(Math.random()*3); // 0~2사이의 난수 만들기
		String com = data[index];

		// 사용자로 부터 가위, 바위, 보 입력 받기
		String man = null;   // 사용자의 가위바위보가 저장될 변수

		// 카운트 다운 쓰레드 실행
		gt.start();

		do{
			man = JOptionPane.showInputDialog("가위, 바위, 보를 입력하세요");
		}while(!man.equals("가위") && !man.equals("바위") && !man.equals("보"));

		inputCheck = true;  // 입력이 완료됨을 알려주는 변수값을 변경한다.

		// 결과 판정하기
		String result = "";
		if( man.equals(com) ){
			result = "비겼습니다.";
		}else if( (man.equals("가위") && com.equals("보"))
				 || (man.equals("바위") && com.equals("가위"))
				 || (man.equals("보") && com.equals("바위")) ){
			result = "당신이 이겼습니다.";
		}else{
			result = "당신이 졌습니다.";
		}

		// 결과 출력
		System.out.println("=== 결 과 ===");
		System.out.println("컴퓨터 : " + com);
		System.out.println("당  신 : " + man);
		System.out.println("결  과 : " + result);
	}

}

게임 타이머

class GameTimer extends Thread{
	@Override
	public void run() {
		for(int i=5; i>=1; i--){
			if(T07_ThreadGame.inputCheck==true){
				return;
			}
			System.out.println(i);
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		System.out.println("시간이 초과되어 당신이 졌습니다.");
		System.exit(0);

	}
}

 

728x90