Java学习-073-多线程06:线程中断 interrupt()
Posted 范丰平
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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()); } }
输出信息如下所示:
以上是关于Java学习-073-多线程06:线程中断 interrupt()的主要内容,如果未能解决你的问题,请参考以下文章