Interrupts

An interrupt is an indication to a thread that it should stop what it is doing and do something else. It's up to the programmer to decide exactly how a thread responds to an interrupt, but it is very common for the thread to terminate. This is the usage emphasized in this lesson.

A thread sends an interrupt by invoking interrupt on the Thread object for the thread to be interrupted. For the interrupt mechanism to work correctly, the interrupted thread must support its own interruption.

Supporting Interruption

How does a thread support its own interruption? This depends on what it's currently doing. If the thread is frequently invoking methods that throw InterruptedException, it simply returns from the run method after it catches that exception. For example, suppose the central message loop in the SleepMessages example were in the run method of a thread's Runnable object. Then it might be modified as follows to support interrupts:

for (int i = 0; i < importantInfo.length; i++) {
// Pause for 4 seconds
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
// We've been interrupted: no more messages.
return;
}
// Print a message
System.out.println(importantInfo[i]);
}

Many methods that throw InterruptedException, such as sleep, are designed to cancel their current operation and return immediately when an interrupt is received.

What if a thread goes a long time without invoking a method that throws InterruptedException? Then it must periodically invoke Thread.interrupted, which returns true if an interrupt has been received. For example:

for (int i = 0; i < inputs.length; i++) {
heavyCrunch(inputs[i]);
if (Thread.interrupted()) {
// We've been interrupted: no more crunching.
return;
}
}

In this simple example, the code simply tests for the interrupt and exits the thread if one has been received. In more complex applications, it might make more sense to throw an InterruptedException:

if (Thread.interrupted()) {
throw new InterruptedException();
}

This allows interrupt handling code to be centralized in a catch clause.

The Interrupt Status Flag

The interrupt mechanism is implemented using an internal flag known as the interrupt status. Invoking Thread.interrupt sets this flag. When a thread checks for an interrupt by invoking the static method Thread.interrupted, interrupt status is cleared. The non-static isInterrupted method, which is used by one thread to query the interrupt status of another, does not change the interrupt status flag.

By convention, any method that exits by throwing an InterruptedException clears interrupt status when it does so. However, it's always possible that interrupt status will immediately be set again, by another thread invoking interrupt.

 
译文:中断
中断是正在执行的线程应该停止并去做其他事情的标志。这需要程序员决定究竟一个线程如何响应中断,但是线程的终止是常见的。这些是本课程的重点。
一个线程通过Thread对象执行interrupt方法向线程发送中断消息。为了使中断机制正常运行,首先需要线程本身支持中断。
中断支持机制
一个线程如何支持它自己的中断呢?这依赖于它现在正在做的事情。如果这个线程频繁的执行抛出interruptedException的方法,这个非常容易从run方法中捕获到这个异常。例如,在sleepMessage实例中假如中央消息循环在实现了runnable接口的run方法中。那么可以修改为如下使它支持中断机制:
 for (int i = 0; i < importantInfo.length; i++) {
// Pause for 4 seconds
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
// We've been interrupted: no more messages.
return;
}
// Print a message
System.out.println(importantInfo[i]);
}

许多方法会抛出interruptException,例如sleep方法,这些方法如果接受到了中断请求就会立刻取消当前正在执行的操作。

如果一个线程运行了很长时间而没有执行抛出interruptedException的方法怎么办?那么它必须定时的执行thread.interrupted方法,当它接受到一个中断后它的返回值是true,例如:

 for (int i = 0; i < inputs.length; i++) {
heavyCrunch(inputs[i]);
if (Thread.interrupted()) {
// We've been interrupted: no more crunching.
return;
}
}

在这个简单的实例中,这段代码只是简单的测试如果存在一个线程接受到了中断请求就会发生中断。在更复杂的应用中,它会抛出一个新的interruptException如下:

 if (Thread.interrupted()) {
throw new InterruptedException();
}

这使得一个catch块儿就能捕获到中断信息。

中断状态标志

中断机制是靠内部的中断状态来实现的。执行thread.interrupt方法时设置这个状态。当一个线程执行thread.interrupted静态方法的时候,中断状态就被清楚掉了。这个非静态的isInterrupted方法是让其他的线程查询这个线程的中断状态的方法,并不改变中断状态。

按照惯例,任何一个抛出interruptedException的方法,当抛出这个异常时都会清楚中断状态,但是,中断状态可能立即被其他的线程调用interrupt方法被重新设置。

养眼是必须滴

【翻译五】java-中断机制的更多相关文章

  1. 多线程(五) java的线程锁

    在多线程中,每个线程的执行顺序,是无法预测不可控制的,那么在对数据进行读写的时候便存在由于读写顺序多乱而造成数据混乱错误的可能性.那么如何控制,每个线程对于数据的读写顺序呢?这里就涉及到线程锁. 什么 ...

  2. 把Scheme翻译成Java和C++的工具

    一.为什么要写这个工具? 公司内容有多个项目需要同一个功能,而这些项目中,有的是用Java的,有的是用C++的,同时由于某些现实条件限制,无法所有项目都调用统一的服务接口(如:可能运行在无网络的情况下 ...

  3. 【转】详细分析Java中断机制

    原文地址:http://www.infoq.com/cn/articles/java-interrupt-mechanism 1. 引言 当我们点击某个杀毒软件的取消按钮来停止查杀病毒时,当我们在控制 ...

  4. 20145213《Java程序设计》实验五Java网络编程及安全

    20145213<Java程序设计>实验五Java网络编程及安全 实验内容 1.掌握Socket程序的编写. 2.掌握密码技术的使用. 3.设计安全传输系统. 实验预期 1.客户端与服务器 ...

  5. 20145206《Java程序设计》实验五Java网络编程及安全

    20145206<Java程序设计>实验五 Java网络编程及安全 实验内容 1.掌握Socket程序的编写: 2.掌握密码技术的使用: 3.设计安全传输系统. 实验步骤 我和201451 ...

  6. 20145337实验五Java网络编程及安全

    20145337实验五Java网络编程及安全 实验内容 掌握Socket程序的编写 掌握密码技术的使用 设计安全传输系统 实验步骤 基于Java Socket实现安全传输 基于TCP实现客户端和服务器 ...

  7. JAVA课程实验报告 实验五 Java网络编程及安全

    北京电子科技学院(BESTI) 实     验    报     告 课程:Java程序设计  班级:1353  姓名:韩玉琪  学号:20135317 成绩:             指导教师:娄嘉 ...

  8. 20145225《Java程序设计》 实验五 Java网络编程及安全

    20145225<Java程序设计> 实验五 Java网络编程及安全 实验报告 一.实验内容 基于Java Socket实现安全传输. 基于TCP实现客户端和服务器,结对编程一人负责客户端 ...

  9. 20145208 实验五 Java网络编程

    20145208 实验五 Java网络编程 实验内容 1.用书上的TCP代码,实现服务器与客户端. 2.客户端与服务器连接 3.客户端中输入明文,利用DES算法加密,DES的秘钥用RSA公钥密码中服务 ...

  10. 20145215实验五 Java网络编程及安全

    20145215实验五 Java网络编程及安全 实验内容 掌握Socket程序的编写: 掌握密码技术的使用: 设计安全传输系统. 实验步骤 本次实验我的结对编程对象是20145208蔡野,我负责编写客 ...

随机推荐

  1. php 简单说明IoC (php 实例+注释)

    简单说明IoC <?php //Ioc ———— 设计方式 //控制反转 Inversion of Control //依赖关系的转移 //依赖抽象而非实践 //用于解决高层应用依赖 底层组件, ...

  2. note:获取字符输入的一些函数

    总是弄混,所以总结一下: getline()     // 接受一个字符串,可以接收空格并输出,需包含“#include<string>” #include<iostream> ...

  3. ubuntu下编译VLC

    ubuntu下编译VLC 标签(空格分隔): ubuntu vlc 视频 编译 [TOC] 1.下载VLC源码包并解压 VLC的源码包在VLC的官网有,可以直接下载.也可以使用git来clone一个. ...

  4. 1.3---字符串重新排列后是否能够变成另一个字符串(CC150)

    import java.util.*; public class Same { public boolean checkSam(String str1, String str2) { // write ...

  5. Yii中的错误及异常处理

    Yii中的错误及异常处理 Yii已经默认已经在CApplication上实现了异常和错误的接管,这是通过php的set_exception_handler, set_error_handler实现的. ...

  6. iframe操作

    http://www.jb51.net/article/15780.htmiframe自适应高度:经典<iframe src="http://www.lanyunwork.com/&q ...

  7. meeting room I & II

    Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si ...

  8. 【leetcode】Validate Binary Search Tree

    Validate Binary Search Tree Given a binary tree, determine if it is a valid binary search tree (BST) ...

  9. iOS 串行网络请求。。。待研究

    nsurlsession 和 nsurlconnection 能实现吗? 手动实现的关键点在哪里? 我这里说的串行网络请求,指的是第一个网络请求不返回数据,第二个网络请求就不能开始. AFNetwor ...

  10. 彻底卸载MySql

    刚装了下MySql,装的过程中由于修改了服务名,导致最后配置假死,不得已,重装. 但是重装时总是失败,于是google了一下,找到彻底卸载mysql的方法: 最近安装本地测试用 MySQL 服务器时总 ...