老师,为什么我在run方法里面用if内套while死循环的方式
做生死牌,结束不了线程?键盘输入后主线程已经结束了子
线程还在跑?
package test01;
import java.io.IOException;
public class StopThread implements Runnable{
boolean flag=true;
//生死牌去控制线程是否执行
@Override
public void run() {
int i=1;
if(flag){
while (flag){
try {
System.out.println(Thread.currentThread().getName()+","+i++);
Thread.currentThread().sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public void stop(){
this.flag=false;
}
public static void main(String[] args) throws IOException {
StopThread st = new StopThread();
Thread t=new Thread(st);
t.start();
int read = System.in.read();
if(read==0){
st.stop();
}
System.out.println("嘻嘻嘻,我结束回家咯!");
}
}