Home  >  Article  >  Java  >  How to stop a thread in java

How to stop a thread in java

PHPz
PHPzforward
2023-05-26 19:04:041543browse

1. Use Interrupt to notify

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

First determine whether the thread is interrupted through Thread.currentThread().isInterrupt(), and then check whether there is still work to be done.

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. Use volatile to mark a field and exit the thread by judging whether the field is true/false

/**
 * 描述:     演示用volatile的局限:part1 看似可行
 */
public class WrongWayVolatile implements Runnable {
 
    private volatile boolean canceled = false;
 
    @Override
    public void run() {
        int num = 0;
        try {
            while (num <= 100000 && !canceled) {
                if (num % 100 == 0) {
                    System.out.println(num + "是100的倍数。");
                }
                num++;
                Thread.sleep(1);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
 
    public static void main(String[] args) throws InterruptedException {
        WrongWayVolatile r = new WrongWayVolatile();
        Thread thread = new Thread(r);
        thread.start();
        Thread.sleep(5000);
        r.canceled = true;
    }
}

The above is the detailed content of How to stop a thread in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete