5.1、线程的五大状态及线程停止

image.png

image.png
线程方法
image.png

通过设置标志位停止线程
package com.example.demo.thread;

/**
 * @projectName: demo
 * @package: com.example.demo.thread
 * @className: TestStop
 * @author:
 * @description: 测试线程停止
 * 1、减一线程正常停止---》利用循环,不建议死循环
 * 2、建议使用标志位---》人为干预
 * 3、不要使用stop或destroy等过时的jdk方法
 * @date: 2021/11/26 17:16
 */
public class TestStop implements Runnable {
    // 1、设置一个标志位
    private boolean flag = true;


    @Override
    public void run() {
        int i = 0;
        while (flag) {
            System.out.println("thread开始!" + i++);
        }
    }

    /**
     * 通过标志位停止线程
     */
    public void stop() {
        flag = false;
        System.out.println("线程停止!");
    }

    public static void main(String[] args) throws InterruptedException {
        TestStop testStop = new TestStop();
        new Thread(testStop).start();
        for (int i = 0; i < 1000; i++) {
            System.out.println("main线程执行第" + i + "次!");
            if (i == 500) {
                testStop.stop();
            }
        }
    }
}
当i=500时thread停止,主线程继续
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容