Java

쓰레드 제어 메소드

KJihun 2023. 5. 29. 20:27
728x90
쓰레드의 제어

출처 : https://velog.io/@jsj3282/Thread%EC%9D%98-%EC%83%81%ED%83%9C

쓰레드의 상태는 위와 같은 그림으로 나타낼 수 있다.

interrupt()

  • interrupt()는 일시정지 상태인 쓰레드를 실행대기 상태로 만든다.

 

sleep()

  • 현재 쓰레드를 지정된 시간 동안 멈추게 한다.
  • 자기 자신에 대해서만 멈추게 할 수 있다.
  • try - catch문을 작성하여야 한다.

join()

  • 정해진 시간 동안 지정한 쓰레드가 작업하는 것을 기다린다.
  • 시간을 지정하지 않았을 때, 지정한 쓰레드의 작업이 끝날 때까지 기다린다.
  • try - catch문을 작성하여야 한다.

join()의 예제

Thread thread = new Thread(task, "thread");

thread.start();

try{
	//join의 괄호안에 값(시간)을 입력하지 않았기 때문에 
    //thread가 작업을 완료할 때 까지 main 쓰레드는 기다림
	thread.join();
    } catch (InterruptedException e) {
    	e.printStackTrace();
    }

 

interrupt()와 sleep()의 예제

 

//람다식을 활용한 쓰레드 생성
Runnable task = () -> {
    
    //Thread가 Interrupted가 아닐 때, 즉 실행대기 상태가 아니라면 수행
	while(!Thread.currentThread().isInterrupted()){
        try{

          //1초마다 출력
          Thread.sleep(1000);
          System.out.println(Thread.currentThread().getName());
          
          //sleep단계에서 interrupte 발생 시 동작
        } catch (InterruptedException e){
          break;
        }
      }
      System.out.println(Thread.currentThread().getName() + " Interrupted");
    };


    Thread thread = new Thread(task, "Thread");

    thread.start();

    try{
      //현재 쓰레드를 5초동안 멈추게 함
      Thread.sleep(5000);
    } catch (InterruptedException e){
      e.printStackTrace();
    }
    
    //쓰레드를 interrupt 시킴
    thread.interrupt();
  }
}