1.不推荐使用JDK提供的stop(),destroy()方法【已经废弃】
2.让线程能够自己停下来
3.建议使用一个标记位进行终止变量,例如:flag=false 责终止线程运行
/**
* @Author: LBC
* @Description:
*/
public class test implements Runnable{
//1.设置一个标识位
private boolean flag = true;
@Override
public void run() {
int i = 0;
while (flag){
System.out.println("还在运行中-----"+i++);
}
}
//2.设置一个公开的方法停止线程在,转换标识位
public void stop(){
this.flag=false;
}
public static void main(String[] args) {
test thread = new test();
new Thread(thread).start();
for(int i=0;i<1000;i++){
System.out.println("主线程运行中-----"+i);
if(i==900){
//调用stop方法切换标记位置,让线程停止
thread.stop();
System.out.println("线程停止-----");
}
}
}
}