关于java:如何优雅的中断线程

2次阅读

共计 1072 个字符,预计需要花费 3 分钟才能阅读完成。

在 Java 中,让一个线程进行工作有以下几种形式

  1. 线程天然执行结束。
  2. 线程执行过程中出现异常并未被解决。
  3. 调用 stop,resume,suspend 办法,这些办法都属于过期的办法,办法调用时不会开释所持有的锁,容易呈现死锁景象。
  4. 应用 interrupt 中断线程。

在 Thread 类中,有如下三个办法

interrupt(): 用于线程中断,该办法并不能间接中断线程,只会将线程的中断标记位改为 true。它只会给线程发送一个中断状态,线程是否中断取决于线程外部对该中断信号做什么响应,若不解决该中断信号,线程就不会中断。
interrupted(): 判断线程是否处于中断状态,该办法调用后会将线程的中断标记位重置为 false。
isInterrupted(): 判断线程是否处于中断状态。

如何平安的进行线程?

public class ThreadTest implements Runnable{

    @Override
    public void run() {
        // 在线程体中对线程的中断标记位进行判断,若线程中断,则不再执行
        while (!Thread.currentThread().isInterrupted()){System.out.println("Thread is running");

            try {System.out.println(Thread.currentThread().getName() + " " + Thread.currentThread().isInterrupted());
                Thread.sleep(100);

            }
            /**
             * 须要留神的是,当办法体中的代码抛出 InterruptedException 异样时,线程的中断标记位会复位成          
             * false,若不解决,内部中断线程时,外部也无奈进行,所以在 catch 代码中手动解决,将线程中断
             */
            catch (InterruptedException e) {System.out.println(Thread.currentThread().getName() + ":" + Thread.currentThread().isInterrupted());
                // 产生 InterruptedException 异样时,在 catch 中解决,中断线程
                Thread.currentThread().interrupt();
                e.printStackTrace();}
            System.out.println(Thread.currentThread().getName() + ":" + Thread.currentThread().isInterrupted());
        }
    }
}
正文完
 0