我们为什么需要线程终止?
线程内代码执行完后,线程会自然进入死亡状态。但如果我们想要手动终止线程,该如何操作呢?
stop()/destroy()
终止线程,Java面向对象的原则,最先想到的应该就是使用Thread类里的方法了吧。
通过查看API,还真有线程的终止方法。但都由于方法有bug,而被弃用了。
所以,不要使用!不要使用!不要使用!(致敬一下《三体》)
标志位法
终止线程,通常的做法是提供一个boolean型的终止变量,当这个变量置为false,则终止线程的运行。
我当年在大学写嵌入式开发时,竟无师自通地用了很多次。直接来个实例感受一下:
public class Test implements Runnable{
private volatile boolean flag = true; //使用volatile修饰
@Override
public void run() {
while(flag) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("线程:"+Thread.currentThread().getName()+" 在听歌");
}
}
void terminate(){
flag = false;
System.out.println("线程:"+Thread.currentThread().getName()+" 终止了");
}
public static void main(String[] args) throws InterruptedException {
Test t1 = new Test();
Test t2 = new Test();
new Thread(t1,"左耳朵").start();
new Thread(t2,"右耳朵").start();
Thread.currentThread().setName("手");
for(int i=0;i<5;i++) {
Thread.sleep(100);
System.out.println("线程:"+Thread.currentThread().getName()+" 在CSND写笔记");
}
t1.terminate();//停止 左耳朵
t2.terminate();//停止 右耳朵
}
}
其中flag使用volatile修饰符是为了保证数据的即时更新。《volatile修饰符》