注意:线程停止不建议使用死循环,使用有次数的循环,建议使用一个标志位,不要使用stop或者destory这些过时的方法 这里的stop方法是我们自定义的stop方法,利用标志位将循环停止
package com.yyf.ThreadStatus;
// 测试线程停止
//1. 建议线程正常停止--》 利用次数,不建议死循环
//2. 建议使用标志位--》 设置一个标志位
//3, 不要使用stop destory 等过时的方法
public class TestThreadStop implements Runnable{
boolean flag=true;
@Override
public void run() {
int i =0;
while(flag){
System.out.println ("run.....thread"+ i++);
}
}
void stop(){
this.flag=false;
}
public static void main(String[] args) {
TestThreadStop s = new TestThreadStop ();
new Thread (s).start ();
for (int i=0; i<=1000;i++){
System.out.println ("main....thread"+i);
if (i==900){
System.out.println ("该线程停止了");
s.stop();
}
}
}
}