【java】5-线程的中断
admin
2024-03-23 08:12:34
0次

1. 线程中断的含义

当我们创建一个线程循环打印语句时,我们想要发出一个指令让该线程停下来,此时,我们可以发送线程中断的命令

线程是否中断实际上是根据一个表示是否中断的标志位来决定的,这个标志位我们既可以自定义,也可以使用Thread内部的一个boolean变量来表示

2. 自定义标志位

class MyRunnable implements Runnable {public volatile boolean isQuit = false;@Overridepublic void run() {while (isQuit == false) {System.out.println("isQuit is false");}System.out.println("isQuit is true");}
}public class Demo15 {public static void main(String[] args) throws InterruptedException {MyRunnable myRunnable = new MyRunnable();Thread t = new Thread(myRunnable);t.start();Thread.sleep(100);myRunnable.isQuit = true;}
}

3. 使用interrupt()方法

一、interrupt()中断对象关联的线程,如果线程正在阻塞,则以异常方式通知,否则设置标志位

public class Demo {public static void main(String[] args) throws InterruptedException {Thread t = new Thread(()->{while (true) {System.out.println("hello");try {Thread.sleep(1000);} catch (InterruptedException e) {System.out.println(Thread.currentThread().isInterrupted());e.printStackTrace();System.out.println("thread is interrupted");break;}}});t.start();Thread.sleep(3000);t.interrupt();}
}

二、Thread.interrupted()判断当前线程的中断标志位是否设置,调用后清除标志位

public class Demo {public static void main(String[] args) throws InterruptedException {Thread t = new Thread(()->{while (!Thread.interrupted()) {System.out.println("hello");}System.out.println(Thread.interrupted());});t.start();Thread.sleep(100);t.interrupt();}
}

三、Thread.currentThread().isInterrupted()判断对象关联的线程的标志位是否设置,调用后不清除标志位

public class Demo {public static void main(String[] args) throws InterruptedException {Thread t = new Thread(()->{while (!Thread.currentThread().isInterrupted()) {System.out.println("hello");}System.out.println(Thread.currentThread().isInterrupted());});t.start();Thread.sleep(100);t.interrupt();}
}

故线程收到通知的方式有两种:

  1. 如果线程因为调用 wait/join/sleep 等方法而阻塞挂起,则以InterruptedException 异常的形式通知,清除中断标志
  2. 当出现 InterruptedException 的时候, 要不要结束线程取决于 catch 中代码的写法. 可以选择忽略这个异常, 也可以跳出循环结束线程.
  3. 否则,只是内部的一个中断标志被设置,thread 可以通过
    Thread.interrupted() 判断当前线程的中断标志被设置,清除中断标志
    Thread.currentThread().isInterrupted() 判断指定线程的中断标志被设置,不清除中断标志

相关内容

热门资讯

AI做攻略、“双向奔赴”……国... 本文转自:人民网人民网记者 许维娜今年国庆假期,AI(人工智能)成了不少年轻人的“旅行搭子”。行前做...
合肥的这个“梗”, 翻篇了 社交平台的评论区,曾长期流传一句专属于合肥的黑色幽默。有人问合肥哪里好玩,本地网友半开玩笑地回复:合...
7万+旅游中高层都在的群,今天... 做旅游这行,资源卡位、渠道互通、项目落地——往往就差一个“对的机会”。我们的行业社群已聚集70,00...
一场帐篷音乐节,如何让井研从“... 帐篷音乐节现场封面新闻记者 周洪攀10月的研溪湿地,晚风里裹着柑橘的清甜与民谣的回响。夜幕降临,10...
白鹤翩翩落星愿,上海迪士尼度假... 10月9日,世界候鸟日前夕,上海迪士尼度假区星愿公园的湖风里多了一分白鹤的灵动。三座白鹤雕塑正式揭幕...
成都锦江边赏初秋枫叶飘飘 目前,成都锦江边国华街枫叶树红了。近年来,国华街附近的几条街都栽种了红枫树,是城区较集中看枫叶的点位...
GBTA:商务旅行正在复苏,但... 亚太正在成为全球商务旅行增长的重要引擎。在经历疫情后的快速反弹之后,全球商务旅行正在进入一个新的增长...
从景区焕新到节赛引流 邹城双节... 齐鲁网·闪电新闻10月9日讯 中秋、国庆“双节”假期,邹城市文化和旅游局提前谋划、周密部署,立足自身...
江山如此多娇 且看石楼今朝 金秋十月,黄河岸畔秋意盎然,丰收盛会喜迎国庆。本次石楼国庆文旅活动以“江山如此多娇,且看石楼今朝”为...
海南国庆假期接待游客475.4... 2026年国庆假期,海南接待游客475.40万人次,较2025年增长13.1%,较2024年增长15...