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

Java에서 실행 중인 스레드를 중단하는 방법은 무엇입니까?

<시간/>

스레드는 스레드 에서 인터럽트를 호출하여 인터럽트를 보낼 수 있습니다. 스레드가 인터럽트될 개체입니다. 즉, 스레드 중단은 interrupt()를 호출하는 다른 스레드에 의해 발생합니다. 방법.

Thread 클래스는 세 가지 인터럽트 메서드를 제공합니다.

  • 무효 인터럽트() - 스레드를 중단합니다.
  • 정적 부울 인터럽트() - 현재 스레드가 중단되었는지 테스트합니다.
  • 부울 isInterrupted() - 스레드가 중단되었는지 테스트합니다.

예시

public class ThreadInterruptTest {
   public static void main(String[] args) {
      System.out.println("Thread main started");
      final Task task = new Task();
      final Thread thread = new Thread(task);
      thread.start();
      thread.interrupt(); // calling interrupt() method
      System.out.println("Main Thread finished");
   }
}
class Task implements Runnable {
   @Override
   public void run() {
      for (int i = 0; i < 5; i++) {
         System.out.println("[" + Thread.currentThread().getName() + "] Message " + i);
         if(Thread.interrupted()) {
            System.out.println("This thread was interruped by someone calling this Thread.interrupt()");
            System.out.println("Cancelling task running in thread " + Thread.currentThread().getName());
            System.out.println("After Thread.interrupted() call, JVM reset the interrupted value to: " + Thread.interrupted());
            break;
         }
      }
   }
}

출력

Thread main started
Main Thread finished
[Thread-0] Message 0
This thread was interruped by someone calling this Thread.interrupt()
Cancelling task running in thread Thread-0
After Thread.interrupted() call, JVM reset the interrupted value to: false