停止一个线程要如何操作

一般来说,我们不需要手动去停止线程,都是等待线程自己停止,或者遇到特殊情况导致线程被动停止。那么我们要停止线程,要怎么才能办到?

public class TestInterrupt {

    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("线程还没感应到中断信号,继续执行");
                }
                System.out.println("----线程感应到中断信号----");
            }
        });
        thread.start(); //启动线程

        Thread.sleep(1000); //休眠1000毫秒也就是1秒

        thread.interrupt(); //中断子线程

        System.out.println("线程的中断状态:" + thread.isInterrupted());
    }
}

在这里插入图片描述
在上面线程收到中断信号后没有立即中断,而是继续运行下去,直到线程内的操作执行完毕后,才关闭线程,这时候调用“ thread.isInterrupted() ”的输出是 true

  • Thread.currentThread().isInterrupted():当前线程是否已经中断?是输出 true,否输出 false
  • thread.interrupt():对线程发出中断信号,通知线程中断,但是否要中断还是要取决于线程本身(就好像街口碰到美女,美女跟你说,帅哥来玩嘛,你去不去不就随你么?不过大家都是正经人,当然是不去啦,我都不用问)

线程在睡眠中,是否能收到中断信号?

public class TestInterrupt {

    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    while (!Thread.currentThread().isInterrupted()) {
                        System.out.println("线程还没感应到中断信号,继续执行");
                        Thread.sleep(3000);
                    }
                } catch (InterruptedException e) {
                    System.out.println("线程收到中断信号,并抛出了异常");
                    e.printStackTrace();
                }
                System.out.println("----线程感应到中断信号----");
            }
        });
        thread.start(); //启动线程

        Thread.sleep(2000); //休眠1000毫秒也就是1秒

        thread.interrupt(); //中断子线程

        System.out.println("线程的中断状态:" + thread.isInterrupted());
    }
}

在这里插入图片描述

答案是可以的,线程在sleep()中的时候,收到中断信号,是会被打断并抛出异常( InterruptedException),并清除中断信号的状态,这时候调用“ thread.isInterrupted() ” 的结果为 false


线程还有一些被丢弃的方法,可以中断线程

例如 stop() 方法,调用stop()方法,会直接把线程给停止掉,并不会通知线程说,我要停止了,你看要不要停止

public class TestInterrupt {

    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("线程还没感应到中断信号,继续执行");
                }
                System.out.println("----线程感应到中断信号----");
            }
        });
        thread.start(); //启动线程

        Thread.sleep(1000); //休眠1000毫秒也就是1秒

        thread.stop(); //中断子线程

        System.out.println("线程的中断状态:" + thread.isInterrupted());
    }
}

欢迎大家关注下个人的「公众号」:独醉贪欢

在C语言中,并没有直接提供的库函数来停止一个线程,因为C标准库本身并不支持线程。但是,如果你使用的操作系统提供了线程API,比如POSIX线程(pthread),你可以通过以下步骤来尝试停止一个线程: 1. **设置退出标志**:通常,在线程启动时会传递一个指向某个值的指针,当需要停止线程时,你可以改变这个值,使其达到特定的终止条件。 ```c volatile sig_atomic_t stop_flag = 0; ``` 2. **检查退出标志**:在线程的循环体内部,检查这个标志是否已经变为非零,如果是,则可以结束线程的执行。 ```c while (!stop_flag) { // 线程的工作代码... if (stop_flag) { break; // 或者使用 pthread_exit() 函数来优雅地退出 } } ``` 3. **使用`pthread_join()`**:如果你想确保主线程等待线程结束后再继续,可以在主线程中使用`pthread_join()`函数。 ```c pthread_join(thread_id, NULL); ``` 4. **取消标记(仅在某些系统上可用)**:如果线程使用了信号量或其他同步机制,有些系统提供了`pthread_cancel()`函数来请求线程提前终止,但这不是所有平台都支持的。 需要注意的是,这并不是标准C库的一部分,而是依赖于特定的操作系统提供的API。在编写这样的代码时,务必查阅所用操作系统文档。另外,线程设计时应尽可能避免硬编码停止操作,而是通过某种约定的通信机制来控制线程的行为。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值