1. 中断线程
中断可以理解为线程的一个标志位属性,它表示一个运行中的线程是否被其他线程进行了中断操作,其他线程通过调用该线程的interrupt()方法对其进行中断操作,线程通过检查自身是否被中断来进行响应,线程通过方法isInterrupt()来进行判断是否被中断,也可以调用静态方法Thread.interrupted()对当前线程的中断标志位进行复位,如果该线程已经处于终结状态,即使该线程被中断过,在调用该线程对象的isInterrupted()时依旧会返回false。
2. 终止处于“阻塞状态”的线程和终止处于“运行状态”的线程
/**
* @Description: 线程中断示例
* @Author: lizhouwei
* @CreateDate: 2018/5/20 21:11
* @Modified By:
*/
public class ThreadInterruptDemo {
public static void main(String[] args) {
//sleepThread线程不停的尝试睡眠
Thread sleepThread = new Thread(new SleepRunner(), "sleepThread");
sleepThread.setDaemon(true);
//busyThread不停的运行
Thread busyThread = new Thread(new BusyRunner(), "busyThread");
busyThread.setDaemon(true);
sleepThread.start();
busyThread.start();
//主线程睡眠5秒,让sleepThread 和busyThread 充分的运行
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
sleepThread.interrupt();//中断阻塞的线程
busyThread.interrupt();//中断正在运行的线程
System.out.println("sleepThread interrupt is " + sleepThread.isInterrupted());
System.out.println("busyThread interrupt is " + busyThread.isInterrupted());
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
System.out.println("1");
e.printStackTrace();
}
}
static class SleepRunner implements Runnable {
@Override
public void run() {
while (true) {
try {
Thread.sleep(100000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
static class BusyRunner implements Runnable {
@Override
public void run() {
while (true) {
}
}
}
}
从结果可以看出,抛出InterruptException 的是被阻塞的线程SleepThread,其中断标志先被设置为true,随后被复位并抛出异常,而正在运行的线程BusyThread,中断标志位没有没被清除。
安全的终止线程
除了使用中断以外,还可以利用一个boolean变量来控制十五终止该线程。
代码示例:
/**
* @Description: 使用boolean变量安全的终止线程
* @Author: lizhouwei
* @CreateDate: 2018/7/1 20:56
* @Modified By:
*/
public class ThreadShutdownDemo {
public static void main(String[] args) {
Runner oneRunner = new Runner();
Thread oneThread = new Thread(oneRunner, "oneThread");
oneThread.start();
//主线程睡眠1秒,主线程对oneThread 线程进行中断,使oneThread能够感知中断而结束
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
oneThread.interrupt();
Runner twoRunner = new Runner();
Thread twoThread = new Thread(twoRunner, "twoThread");
twoThread.start();
//主线程睡眠1秒,主线程对twoThread 线程进行中断,使twoThread能够感知中断而结束
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
twoRunner.cancel();
}
private static class Runner implements Runnable {
private long i;
private volatile boolean running = true;
@Override
public void run() {
while (running && !Thread.currentThread().isInterrupted()) {
i++;
}
System.out.println("count i = " + i);
}
public void cancel() {
running = false;
}
}
}
运行结果