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停止,主线程继续