Java没有提供任何机制来安全地终止线程,但是它提供了中断(Interruption).这是一种协作机制,能够使一个线程终止另一个线程当前的工作。
在对一个线程对象调用Thread.interrupted()方法之后,一般情况下对这个线程不会产生任何影响。因为调用Thread.interrupted()方法只是将增线程的中断标志位设置为true。
如果一个线程被调用Thread.interrupted()方法之后,如果它的状态是阻塞状态或者是等待状态,而且这个状态正是因为正在执行的wait、join、sleep线程造成的,那么是会改变运行的结果(抛出InterruptException异常)
1.线程终止
由于Java没有提供任何机制来安全地终止线程,那么我们应该如何终止线程呢?下面我们提供三种线程终止的方法:
使用退出标志,使线程正常退出,也就是当run方法完成后线程终止。
使用stop方法强行终止线程(这个方法不推荐使用,因为stop和suspend、resume一样,也可能发生不可预料的结果)。
使用interrupt方法中断线程。
1.1 使用退出标志
当run方法执行完后,线程就会退出。但有时run方法是永远不会结束的。如在服务端程序中使用线程进行监听客户端请求,或是其他的需要循环处理的任务。在这种情况下,一般是将这些任务放在一个循环中,如while循环。如果想让循环永远运行下去,可以使用while(true){……}来处理。但要想使while循环在某一特定条件下退出,最直接的方法就是设一个boolean类型的标志,并通过设置这个标志为true或false来控制while循环是否退出。
public class ThreadFlag implements Runnable{
private volatile boolean exit=false;
@Override
public void run() {
while (!exit){
///do something
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("-----------ThreadFlag shutdown----------");
}
public static void main(String[] args) throws InterruptedException {
ThreadFlag threadFlag=new ThreadFlag();
Thread thread=new Thread(threadFlag);
thread.start();
Thread.sleep(3000);
threadFlag.exit=true;
thread.join();
System.out.println("线程退出");
}
}
上面代码使用了一个线程标志位来判断线程是否关闭.通过对线程标志位进行操作来决定线程是否关闭.
1.2 使用stop方法终止线程
使用stop方法可以强行终止正在运行或挂起的线程。我们可以使用如下的代码来终止线程:
public class ThreadStop implements Runnable {
@Override
public void run() {
try {
while (true){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} finally {
System.out.println("-----------ThreadStop shutdown----------");
}
}
public static void main(String[] args) throws InterruptedException {
ThreadStop threadStop=new ThreadStop();
Thread thread=new Thread(threadStop);
thread.start();
Thread.sleep(3000);
thread.stop();
System.out.println("线程退出");
}
}
这种方法线程不安全,Java不建议使用这种stop方法关闭线程。
1.3 使用interrupt方