Thread예제3(Runnable): 난수더하기

·2022년 11월 3일
0

JAVA객체지향_Thread

목록 보기
4/7

임의의 난수(1~10)를 두개 더해서 맞추는 프로그램

제한시간은 60초

1. 사용할 클래스

Random, Scanner

2.큰 틀 작성 : 인터페이스 구현 클래스, main메소드

//덧셈스레드
class SumThread implements Runnable{
	@Override
	public void run(){
    }
}
//제한시간 스레드
class TimeAttackThread implements Runnable{
	@Override
    public void run(){
    }
}
//main 메소드
public class Test{
	public static void main(String[]args){
    	new Thread(new SumThread()).start();
        new Thread(new TimeAttackThread()).start();
    }
}

3. 구현부 작성

//덧셈스레드(난수 덧셈, 맞춘개수, 정답/오답)
class SumThread implements Runnable{
	//다른 클래스로 가져가기 위해 static 변수 생성
	Static int cnt;
	@Override
	public void run(){
    	while(true){
        	Random r = new Random();
            int a = r.nextInt(10)+1;
            int b = r.nextInt(10)+1;
            System.out.println(a+"+"+b+"=");
            int c = sc.nextInt(); //답입력
            //정답
            if(c==(a+b)){
              cnt++;
              System.out.println("정답입니다. 맞춘개수: "+cnt);
           //오답
            }else{
              System.out.println("틀렸습니다. 맞춘개수: "+cnt);
          	}
      }
}
//제한시간 스레드
class TimeAttackThread implements Runnable{
	@Override
    public void run(){
    	int count=0; //초세기 변수
        while(true){
       	//1초 지날때마다 count 1씩 증가
          count++;
          //60초가 지나면 종료문구와 맞춘개수 출력
          if(count==60){
          	System.out.println("덧셈이 종료되었습니다.");
            System.out.println("맞춘개수: "+SumThread.cnt); //SumThread의 cnt를 리턴
            //다른 클래스의 변수를 가져오려면 해당 변수가 Static변수여야 함
            System.exit(0); //프로그램 종료
          }else if(count%10==0){
          	System.out.println((60-count)+"초 남았습니다.");
          }
          try{
          	//스레드 1초 지연
          	Thread.sleep(1000);
          }catch(InterruptedException ie){
              System.out.println(ie.getMessage());
          }
    }
}
//main 메소드
public class Test{
	public static void main(String[]args){
    	new Thread(new SumThread()).start();
        new Thread(new TimeAttackThread()).start();
    }
}
profile
웹개발입문자

0개의 댓글