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

How to stop a thread in java

PHPz
Release: 2023-05-26 19:04:04
forward
1618 people have browsed it

1. Use Interrupt to notify

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

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();
    }
 
}
Copy after login

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;
    }
}
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template