编程语言
首页 > 编程语言> > Java学习-073-多线程06:线程中断 interrupt()

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

作者:互联网

当一个线程运行时,另外一个线程可以直接通过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());
    }
}

 

输出信息如下所示:

 

标签:info,06,073,Thread,getName,线程,多线程,threadInterrupt,log
来源: https://www.cnblogs.com/fengpingfan/p/14701482.html