Computer >> 컴퓨터 >  >> 프로그램 작성 >> Java

스레드가 Java에서 다른 스레드를 어떻게 인터럽트할 수 있습니까?

<시간/>

InterruptedException 예외의 도움으로 스레드 실행을 인터럽트하기 위해 Java에서 '인터럽트' 기능을 사용할 수 있습니다.

아래 예는 현재 실행 중인 스레드가 인터럽트되면 (catch 블록에서 발생한 새로운 예외 때문에) 실행을 중지하는 방법을 보여줍니다. -

public class Demo extends Thread
{
   public void run()
   {
      try
      {
         Thread.sleep(150);
         System.out.println("In the 'run' function inside try block");
      }
      catch (InterruptedException e)
      {
         throw new RuntimeException("The thread has been interrupted");
      }
   }
   public static void main(String args[])
   {
      Demo my_inst = new Demo();
      System.out.println("An instance of the Demo class has been created");
      my_inst.start();
      try
      {
         my_inst.interrupt();
      }
      catch (Exception e)
      {
         System.out.println("The exception has been handled");
      }
   }
}

출력

An instance of the Demo class has been created
Exception in thread "Thread-0" java.lang.RuntimeException: The thread has been interrupted
at Demo.run(Demo.java:12)

Demo라는 클래스는 Thread 클래스를 확장합니다. 여기 'try' 블록 내부에 'run'이라는 이름의 함수가 정의되어 이 함수를 150밀리초 동안 휴면 상태로 만듭니다. 'catch' 블록에서 예외가 catch되고 콘솔에 관련 메시지가 표시됩니다.

메인 함수에서 Demo 클래스의 인스턴스가 생성되고 'start' 함수를 사용하여 스레드가 시작됩니다. 'try' 블록 내에서는 인스턴스가 인터럽트되고, 'catch' 블록에서는 예외를 나타내는 관련 메시지가 출력됩니다.