1、线程中断:
java中的线程中断是一种线程间的协作模式,通过设置线程的中断标志并不能直接终止该线程的执行,而是被终端的线程根据中断状态自行处理。
- void interrupt()方法:中断线程,例如,当线程A运行时,线程B可以调用线程A的interrupt()方法来设置线程A的中断标志为true并立即返回。设置标志仅仅是设置标志,线程A实际并没有被中断,它会继续执行下去。如果线程A因为调用了wait系列函数、join方法或者sleep方法而被阻塞挂起,这时候若线程B调用线程A的interrupt()方法,线程A会在调用这些方法的地方抛出InterruptedException异常而返回。
- boolean isInterrupted()方法:检测当前线程石佛iu被中断,如果是返回true,否则返回false。
-
public boolean isInterrupted() { // 传递false,说明不清除中断标志 return isInterrupted(false); }
- boolean interrupted()方法:检测当前线程是否被中断,如果是返回true,否则返回false。与isInterrupted不同的是,该方法如果发现当前线程被中断,则会清除中断标志,并且该方法是static方法,可以通过Thread类直接调用。如果本次调用了清除操作,则返回true,否则返回false。举个例子:如果stopFlag为true,调用interrupted(),则stopFlag将被设置为false,同时函数返回true.如果stopFlag为false,调用interrupted(),则直接返回false.
-
public static boolean interrupted() { // 清除中断标志 return currentThread().isInterrupted(true); }
- 从上面的代码可以看出,在interrupted()内部是获取当前调用线程的中断标志而不是调用interrupted()方法的实例对象的中断标志。
1.1、根据中断标志判断线程是否终止
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
// 如果当前线程被中断则退出循环
while (!Thread.currentThread().isInterrupted())
System.out.println(Thread.currentThread() + "hello");
}
});
// 启动子线程
thread.start();
// 主线程休眠1s,以便中断前让子线程输出
Thread.sleep(1000);
// 中断子线程
System.out.println("main thread interrupt thread");
thread.interrupt();
// 等待子线程执行完毕
thread.join();
System.out.println("main is over");
}
1.2、提前返回
当线程为了等待一些特定条件的到来时,一般会调用sleep函数、wait系列函数或者join()函数来阻塞挂起当前线程。比如一个线程调用了Thread.sleep(3000),那么调用线程会被阻塞,直到3s后才从阻塞状态变为激活状态。但是有可能在3s内条