java自学之路—线程的终止

138 阅读2分钟

「这是我参与2022首次更文挑战的第8天,活动详情查看:2022首次更文挑战

Hope is a good thing, maybe the best of things. And no good thing ever dies—— 《The Shawshank Redemption》

前言

Java 本身的概念还是比较多的,所以学习的开始还是要先打好基础,从一些基本的概念入手,这些都是Java的一些常识。在Java的面试中都是很重要的东西。

上一篇内容我们学习了线程启动的三种方式,今天来聊聊线程的终止。线程的终止在Java语言中有很多种情况,我们一个个的介绍一下。

正常终止

当线程运行完毕,run() 执行完毕并正常退出,这个时候系统会释放资源,我称之为自然终止或者正常终止

异常终止

当线程在运行过程中,出现了未知的异常,JVM 也会终止程序。这种抛出位置异常的终止,我们称之为异常终止。异常终止往往会给用户带来很差的体验,我们不应该是对此视而不见,所以我们应该保证我们的程序能优雅的终止,让每个程序都能功成身退。

被强制终止

调用stop()方法强制终止,Thread 类中有一个stop()方法可以调用,但是我们在实际的开发中是不建议使用的,这个方法已经过时。

源码如下:

@Deprecated
public final void stop() {
    SecurityManager security = System.getSecurityManager();
    if (security != null) {
        checkAccess();
        if (this != Thread.currentThread()) {
            security.checkPermission(SecurityConstants.STOP_THREAD_PERMISSION);
        }
    }
    // A zero status value corresponds to "NEW", it can't change to
    // not-NEW because we hold the lock.
    if (threadStatus != 0) {
        resume(); // Wake up thread if it was suspended; no-op otherwise
    }

    // The VM can handle all thread states
    stop0(new ThreadDeath()); 
}

请求中断线程

请求中断线程使用的是 interrupt 相关的方法进行中断线程。

interrupt()isInterrupted() 方法

package stop;

public class InterruptThread {
   public static void main(String[] args) {
       Runnable runnableThreadImp = () -> {
           Thread currentThread = Thread.currentThread(); // 获取当前线程
           // 判断当前线程是否已经是中断状态
           while (!currentThread.isInterrupted()) {
               System.out.print("Runnable Thread");
           }
       };
       Thread runnable = new Thread(runnableThreadImp);
       runnable.start();

       try {
           Thread.sleep( 20 ); // 让主线程休眠20ms
       } catch (InterruptedException e) {
           e.printStackTrace();
       }


       // 请求中断线程,即设置当前线程的中断状态为true
       runnable.interrupt();
   }
}

interrupted() 方法

我们可能不会直接去中断线程,在线程终止前会有其他的事情要做。

package stop;

public class InterruptThread {
   public static void main(String[] args) {
       Runnable runnableThreadImp = () -> {
           Thread currentThread = Thread.currentThread();
           // while (!currentThread.isInterrupted()) {
           // 清楚当前线程的中断状态为false,以便响应其它的情况
           while (!Thread.interrupted() /* && 其它条件 */) {
               System.out.print("Runnable Thread");
               // TODO 清理工作
           }
       };
       Thread runnable = new Thread(runnableThreadImp);
       runnable.start();

       try {
           Thread.sleep( 20 ); // 让主线程休眠20ms
       } catch (InterruptedException e) {
           e.printStackTrace();
       }


       // 请求中断线程,即设置当前线程的中断状态为true
       runnable.interrupt();
   }
}

结语

如果这篇文章帮到了你,欢迎点赞👍和关注⭐️。

文章如有错误之处,希望在评论区指正🙏🙏

欢迎关注我的微信公众号,一起交流技术,微信搜索 🔍 :「 五十年以后