大佬们帮忙看下,刚刚学线程的终止,为什么写完之后不能准确终止线程呢?
public class TestThread08 {
public static void main(String[] args) throws InterruptedException {
MyThread5 m5 =new MyThread5();
Thread t =new Thread(m5);
t.setName("睡眠线程");
t.start();
//5秒后终止线程
Thread.sleep(5000);
m5.run = false;
}
}
class MyThread5 implements Runnable{
public boolean run = true;
@Override
public void run() {
if(run == true){
for(int i=0; i<10; i++){
try {
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName()+"-->"+i);
} catch (InterruptedException e) {
//e.printStackTrace();
}
}
}else {
return;
}
}
}