首页 > 编程语言 > 详细

Java学习-073-多线程06:线程中断 interrupt()

时间:2021-05-16 19:20:03      阅读:34      评论:0      收藏:0      [点我收藏+]

当一个线程运行时,另外一个线程可以直接通过interrupt()方法中断其运行状态。示例代码如下所示:

package com.fanfengping.demo;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class Demo10RunnableInterrupt implements Runnable {
    @Override
    public void run() {
        log.info("{} 开始运行", Thread.currentThread().getName());

        try {
            log.info("{} 模仿线程在处理任务", Thread.currentThread().getName());
            // 模仿线程在处理任务
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            log.error(Thread.currentThread().getName() + " 被中断", e);
        }
    }

    public static void main(String[] args) {
        Demo10RunnableInterrupt demo10RunnableInterrupt = new Demo10RunnableInterrupt();

        Thread threadInterrupt = new Thread(demo10RunnableInterrupt, "Interrupt_demo");

        log.info("{} 运行状态:{},是否存活:{},是否被中断:{}", threadInterrupt.getName(), threadInterrupt.getState().name(), threadInterrupt.isAlive(), threadInterrupt.isInterrupted());

        threadInterrupt.start();
        try {
            log.info("{} 运行状态:{},是否存活:{},是否被中断:{}", threadInterrupt.getName(), threadInterrupt.getState().name(), threadInterrupt.isAlive(), threadInterrupt.isInterrupted());
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("{} 运行状态:{},是否存活:{},是否被中断:{}", threadInterrupt.getName(), threadInterrupt.getState().name(), threadInterrupt.isAlive(), threadInterrupt.isInterrupted());
        threadInterrupt.interrupt();
        log.info("{} 运行状态:{},是否存活:{},是否被中断:{}", threadInterrupt.getName(), threadInterrupt.getState().name(), threadInterrupt.isAlive(), threadInterrupt.isInterrupted());
    }
}

 

输出信息如下所示:

技术分享图片

 

Java学习-073-多线程06:线程中断 interrupt()

原文:https://www.cnblogs.com/fengpingfan/p/14701482.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!