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. String与InputStream互转的几种方法

    [java] view plain copy /** * 利用BufferedReader实现Inputstream转换成String <功能详细描述> * * @param in * @ ...

  2. SVN的目录说明

    subversion目录说明:*dav目录:是提供apache与mod_dav_svn使用的目录,让他们存储内部数据*db目录:就是所有版本控制的数据存放文件*hooks目录:放置hook脚本文件的目 ...

  3. python协程

    http://bingotree.cn/?p=63 协程与yield的介绍,轻松搞笑. http://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d ...

  4. 把strassen乘法调出来了...

    完美... 指针搞死我了 /// /// Author: zball /// No rights reserved /// (Creative Commons CC0) /// #include &l ...

  5. openstack 常用命令

    转自: docs.openstack.org $ nova boot --image ubuntu-cloudimage --flavor 1 --user-data mydata.file

  6. 【leetcode】Permutations II

    Permutations II Given a collection of numbers that might contain duplicates, return all possible uni ...

  7. UIImage 在某些控件上被放大问题

    今天用到了UISlider,想利用slider.setThumbImage(UIImage(named:"aaa"), forState: UIControlState.Norma ...

  8. ACM/ICPC 之 平面几何-两直线关系(POJ 1269)

    题意:给定四点的坐标(x,y),分别确定两直线,求出其交点,若重合or平行则输出相应信息 用四个点的坐标算出直线通式(ax+by+c=0)中的a,b,c,然后利用a,b,c计算出交点坐标(其他公式不够 ...

  9. Maven 安装

    简单记录maven的安装步骤: 在安装maven之前,先确保已经安装JDK1.6及以上版本,并且配置好环境变量. 下载maven3,最新版本是Maven3.2.3 ,下载地址:http://maven ...

  10. css 发光字效果

    <!DOCTYPE html> <html> <head> <!-- 超酷炫的CSS3发光字体,可自定义喔!!--> <meta http-equ ...