>  기사  >  Java  >  Java에서 스레드를 중지하는 방법

Java에서 스레드를 중지하는 방법

PHPz
PHPz앞으로
2023-05-26 19:04:041544검색

1. 인터럽트를 사용하여 알림

while (!Thread.currentThread().isInterrupted() && more work to do) {     do more work    }

먼저 Thread.currentThread().isInterrupt()를 사용하여 스레드가 중단되었는지 확인한 다음 아직 수행해야 할 작업이 있는지 확인합니다.

public class StopThread implements Runnable {
 
    @Override
    public void run() {
 
        int count = 0;
 
        while (!Thread.currentThread().isInterrupted() && count < 1000) {
 
            System.out.println("count = " + count++);
 
        }
 
    }
 
    public static void main(String[] args) throws InterruptedException {
 
        Thread thread = new Thread(new StopThread());
        thread.start();
        Thread.sleep(5);
        thread.interrupt();
    }
 
}

2 휘발성을 사용하여 필드를 표시하고 필드가 true/false인지 판단하여 스레드를 종료합니다.

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

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