Java 实例 - 中断线程

Java 教程 · 2019-02-12 07:57:13

以下实例演示了如何使用interrupt()方法来中断线程并使用 isInterrupted() 方法来判断线程是否已中断:

Main.java 文件

public class Main extends Object implements Runnable { public void run() { try { System.out.println("in run() - 将运行 work2() 方法"); work2(); System.out.println("in run() - 从 work2() 方法回来"); } catch (InterruptedException x) { System.out.println("in run() - 中断 work2() 方法"); return; } System.out.println("in run() - 休眠后执行"); System.out.println("in run() - 正常离开"); } public void work2() throws InterruptedException { while (true) { if (Thread.currentThread().isInterrupted()) { System.out.println("C isInterrupted()=" + Thread.currentThread().isInterrupted()); Thread.sleep(2000); System.out.println("D isInterrupted()=" + Thread.currentThread().isInterrupted()); } } } public void work() throws InterruptedException { while (true) { for (int i = 0; i < 100000; i++) { int j = i * 2; } System.out.println("A isInterrupted()=" + Thread.currentThread().isInterrupted()); if (Thread.interrupted()) { System.out.println("B isInterrupted()=" + Thread.currentThread().isInterrupted()); throw new InterruptedException(); } } } public static void main(String[] args) { Main si = new Main(); Thread t = new Thread(si); t.start(); try { Thread.sleep(2000); } catch (InterruptedException x) { } System.out.println("in main() - 中断其他线程"); t.interrupt(); System.out.println("in main() - 离开"); } }

以上代码运行输出结果为:

in run() - 将运行 work2() 方法
in main() - 中断其他线程
in main() - 离开
C isInterrupted()=true
in run() - 中断 work2() 方法

点击查看所有 Java 教程 文章: https://www.codercto.com/courses/l/12.html

查看所有标签

C++编程风格

C++编程风格

卡吉尔 / 聂雪军 / 机械工业出版社发行室 / 2007-1 / 25.00元

本书描述C++语言中较深层次的程序设计思想和使用方法,包含大量软件工程概念和设计模式,重点介绍大规模编程相关的内容,例如增加代码的可读性、可维护性、可扩展性以及执行效率等的方法。本书的示例代码都是从实际程序中抽取出来的,融人了作者的实际开发经验。讲解如何正确地编写代码以及避开一些常见的误区和陷阱,并给出了许多实用的编程规则,可快速提升读者的C++编程功力。   本书描述平实,示例丰富,适合有......一起来看看 《C++编程风格》 这本书的介绍吧!

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具