JAVA笔记概览
来源:互联网 发布:域名查询软件西部数码 编辑:程序博客网 时间:2024/05/17 02:33
相关方法
- interrupt()
- isInterrupted()
第一种情况
public class Test { public static void main(String[] args) { Thread t = new T(); t.start(); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } t.interrupt(); }}class T extends Thread { @Override public void run() { int count = 0; while (true) { System.out.println("--- " + count + " ---"); if (Thread.currentThread().isInterrupted()) { System.out.println("Thread has interrupted"); break; } ++count; } }}
执行结果:
正常中断
....--- 394930 ------ 394931 ------ 394932 ---Thread has interrupted
第二种情况
public class Test { public static void main(String[] args) { Thread t = new T(); t.start(); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } t.interrupt(); }}class T extends Thread { @Override public void run() { int count = 0; while (true) { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("--- " + count + " ---"); if (Thread.currentThread().isInterrupted()) { System.out.println("Thread has interrupted"); break; } ++count; } }}
执行结果:
线程没有中断, 中间抛出了个 异常 但是 继续执行
..--- 8 ------ 9 ---java.lang.InterruptedException: sleep interrupted at java.lang.Thread.sleep(Native Method) at aaa.T.run(Test.java:30)--- 10 ------ 11 ---..
原理分析:
If this thread is blocked in an invocation of the wait(), wait(long), or wait(long, int) methods of the Object class, or of the join(), join(long), join(long, int), sleep(long), or sleep(long, int), methods of this class, then its interrupt status will be cleared and it will receive an InterruptedException.
-> 如果 遇到 sleep(或其他) 解除中断
, 并抛出 InterruptedException 异常
.
第二种情况解决
思路:
1. 既然状态会被清楚, 咱就不用原来的状态(咱也看不到) 自己定义一个状态
2. 在抛异常的时候 中断状态 改为 true
public class Test { public static void main(String[] args) { Thread t = new T(); t.start(); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } t.interrupt(); }}class T extends Thread { // 定义一个 标记 表示 是否 中断 private static boolean status = false; @Override public void run() { int count = 0; while (true) { try { Thread.sleep(100); } catch (InterruptedException e) { // 抛出异常的同时 改变 状态 status = true; // 这里就不捕获异常了 // e.printStackTrace(); } System.out.println("--- " + count + " ---"); // 使用自定义中断状态判断 if (status) { System.out.println("Thread has interrupted"); break; } ++count; } }}
阅读全文
0 0
- JAVA笔记概览
- JAVA笔记概览
- JAVA笔记概览
- JAVA笔记概览
- JAVA笔记概览
- Java Web笔记:JSP的九大内置对象概览
- Java语言 -- 概览
- Java技术概览
- java 输入输出流概览
- java web前台概览
- java学习概览
- Java 集合概览
- Java网络编程概览
- Java 集合概览
- Java编译概览
- Java集合概览
- java多线程并发概览
- Java流、IO概览
- [codevs1391]伊吹萃香
- sizeof(类)
- linux C++获取目录下文件列表
- inner join left right full +
- JSP学习笔记
- JAVA笔记概览
- leetcode399 Evaluate Division
- BigInteger类用于表示比long更大的整数类型
- C语言 sizeof函数详解
- 对于arm嵌入式系统的一点认识
- SpringBoot启动时的Banner设置
- java 8 新特性
- 堆和栈的区别(转过无数次的文章)
- 扩展欧几里得