1. Thread.stop()函数
stop()函数终止线程就像是强行拔掉电源线关机一样,可能会带来未知风险,因此目前不再推荐使用这种方式。请忘记它吧~~
2. 改变标志变量状态
通常我们会在线程中使用一个标志变量来控制线程的运行,如:
public class TestCallable implements Runnable {
private boolean running = true;
public void stop() {
this.running = false;
}
public void run() {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while (running) {
System.out.println("线程正在运行中...");
Thread.sleep(20000);
}
System.out.println("线程被终止.");
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
try {
TestCallable callable = new TestCallable();
Thread th = new Thread(callable);
th.start();
Thread.sleep(1000);
callable.stop();
System.out.println("已下达终止线程命令。");
} catch (Exception e) {
e.printStackTrace();
}
}
}
执行上述代码就能发现,线程阻塞在reader.readLine()时,即使主线程改变了标志变量,但是并不能立即结束子线程,只有等待阻塞被打破,且运行到下一次循环条件判断的时候才能终止。所以在使用这种方法时,应该考虑到阻塞这种情况。当然,如果整个循环内的操作属于同一事务时,这种方法倒很不错。
3. 中断函数interrupt()
网上有很多论调说,终止线程的正确处理方式是使用interrupt中断,但真的是这样吗?实践出真知,拭目以待吧!
如上2所述,如果线程中有Thread.sleep()阻塞时,改变标识变量无法达到终止线程的目的,那么此时可以使用Thread类的中断函数interrupt();
如:
public class TestCallable extends Thread {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
public void stopThread() {
interrupt();
}
public void run() {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
reader.close();
while (!isInterrupted()) {
System.out.println("线程正在运行中...");