商城首页欢迎来到中国正版软件门户

您的位置:首页 >java怎么停止线程

java怎么停止线程

  发布于2023-05-04 阅读(0)

扫一扫,手机访问

1、使用Interrupt来通知 

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、使用volatile标志一个字段,通过判断这个字段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;
    }
}
本文转载于:https://www.yisu.com/zixun/581631.html 如有侵犯,请联系zhengruancom@outlook.com删除。
免责声明:正软商城发布此文仅为传递信息,不代表正软商城认同其观点或证实其描述。

热门关注