线程的停止

本文探讨了线程终止的多种方式,包括使用interrupt方法和volatile变量。详细解释了interrupt方法的工作原理,以及如何通过volatile变量控制线程终止,避免直接使用已废弃的stop方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

      线程的停止 线程的启动过程大家都非常熟悉,但是如何终止一个线程,我相信绝大部分人 在面试的时候被问到这个问题时,也会不知所措,不知道怎么回答。

      线程的终止,并不是简单的调用 stop 命令去。虽然 api 仍然可以调用, 但是和其他的线程控制方法如 suspend、resume 一样都是过期了的不建议使 用,就拿 stop 来说,stop 方法在结束一个线程时并不会保证线程的资源正常 释放,因此会导致程序可能出现一些不确定的状态。

      要优雅的去中断一个线程,在线程中提供了一个 interrupt 方法 interrupt 方法 当其他线程通过调用当前线程的 interrupt 方法,表示向当前线程打个招呼, 告诉他可以中断线程的执行了,至于什么时候中断,取决于当前线程自己。 线程通过检查资深是否被中断来进行相应,可以通过 isInterrupted()来判断是 否被中断。 通过下面这个例子,来实现了线程终止的逻辑

package com.example.demo.morethread;

import java.util.concurrent.TimeUnit;

public class InterreptDemo {
    private static int i=1;
    public static void main(String[] args) throws InterruptedException {

        Thread thread=new Thread(()->{
            while (true){
                while (!Thread.currentThread().isInterrupted()){
                    i++;
                    System.out.println("i:"+i);
                }
                System.out.println("num:"+i);
            }
        },"thread");
        thread.start();
        TimeUnit.SECONDS.sleep(1);
        //中断线程
        thread.interrupt();
    }
}

运行结果如下:

除了通过 Thread.interrupted 方法对线程中断标识进行复位以外,还有一种被 动复位的场景,就是对抛出 InterruptedException 异常的方法,在 InterruptedException 抛出之前,JVM 会先把线程的中断标识位清除,然后才 会抛出 InterruptedException,这个时候如果调用 isInterrupted 方法,将会 返回 false

package com.example.demo.morethread;

import java.util.concurrent.TimeUnit;

public class InterreptDemo {
    private static int i=1;
    public static void main(String[] args) throws InterruptedException {

        Thread thread=new Thread(()->{
            while (true){
                boolean flag=Thread.currentThread().isInterrupted();
                if(flag){
                    System.out.println("before:"+flag);
                    Thread.interrupted();//线程复位
                    System.out.println("after:"+Thread.currentThread().isInterrupted());
                }

            }
        },"thread");
        thread.start();
        TimeUnit.SECONDS.sleep(1);
        //中断线程
        thread.interrupt();
        TimeUnit.SECONDS.sleep(1);
        System.out.println(Thread.currentThread().isInterrupted());
    }
}

运行结果如下:

除了通过 interrupt 标识为去中断线程以外,我们还可以通过下面这种方式, 定义一个 volatile 修饰的成员变量,来控制线程的终止。这实际上是应用了 volatile 能够实现多线程之间共享变量的可见性这一特点来实现的。
 

public class VolatileDemo {

private volatile static boolean stop=false; 

public static void main(String[] args) throws InterruptedException {

Thread thread=new Thread(()->{
 int i=0; while(!stop){ i++; 
} 
}); 
thread.start(); 
System.out.println("begin start thread"); 
Thread.sleep(1000); 
stop=true; 
} 
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值