>  기사  >  Java  >  Java에서 스레드를 어떻게 중지합니까?

Java에서 스레드를 어떻게 중지합니까?

WBOY
WBOY앞으로
2023-09-13 17:21:031033검색

Java에서 스레드를 어떻게 중지합니까?

Java에서 Thread 클래스의 stop() 메서드를 호출하여 실행 중인 스레드를 중지하려고 할 때마다 이 메서드는 실행 중인 스레드의 실행을 중지하고 이를 대기 스레드 풀에서 제거하고 가비지 수집합니다. 스레드가 메서드 끝에 도달하면 자동으로 종료 상태로 전환됩니다. 스레드 안전 문제로 인해 Java에서 stop() 메서드가 더 이상 사용되지 않습니다.

구문

@Deprecated
public final void stop()

import static java.lang.Thread.currentThread;
public class ThreadStopTest {
   public static void main(String args[]) throws InterruptedException {
      UserThread userThread = new UserThread();
      Thread thread = new Thread(userThread, "T1");
      thread.start();
      System.out.println(currentThread().getName() + " is stopping user thread");
      userThread.<strong>stop()</strong>;
      Thread.sleep(2000);
      System.out.println(currentThread().getName() + " is finished now");
   }
}
class UserThread implements Runnable {
   private volatile boolean exit = false;
   public void run() {
      while(!exit) {
         System.out.println("The user thread is running");
      }
      System.out.println("The user thread is now stopped");
   }
   public void stop() {
      exit = true;
   }
}

출력

main is stopping user thread
The user thread is running
The user thread is now stopped
main is finished now

위 내용은 Java에서 스레드를 어떻게 중지합니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 tutorialspoint.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제