본문 바로가기

Back/Java

[JAVA/멀티스레드] JAVA멀티스레딩 - 스레드종료 및 데몬스레드 퀴즈

퀴즈1

    public static void main(String [] args) {
        Thread thread = new Thread(new WaitingForUserInput());
        thread.setName("InputWaitingThread");
        thread.start();
    }
 
    private static class WaitingForUserInput implements Runnable {
        @Override
        public void run() {
            try {
                while (true) {
                    char input = (char) System.in.read();
                    if(input == 'q') {
                        return;
                    }
                }
            } catch (IOException e) {
                System.out.println("An exception was caught " + e);
            };
        }
    }


System.in.read()는 Thread.interrupt()에 응답하지않는다.
애플리케이션을 중단하기위해 다음과 같은 방법을 이용할 수 있다

  1. 사용자가 ‘q'를 입력해서 나오는 방법
  2. 스레드 시작전 데몬스레드로 설정하는방법
  3. 애플리케이션을 강제종료 하는 방법



퀴즈2

    public static void main(String [] args) {
        Thread thread = new Thread(new SleepingThread());
        thread.start();
        thread.interrupt();
    }
 
    private static class SleepingThread implements Runnable {
        @Override
        public void run() {
            while (true) {
                try {
                    Thread.sleep(1000000);
                } catch (InterruptedException e) {
                }
            }
        }
    }

위 코드는 애플리케이션을 중단할 수 없다.
InterruptedException catch 블록안에
return; 을 추가해서 애플리케이션을 중단할 수 있다.