src: http://www.informit.com/articles/article.aspx?p=26326&seqNum=3

Interrupting Threads

A thread terminates when its run method returns. (In the first version of the Java programming environment, there also was astop method that another thread could call to terminate a thread. However, that method is now deprecated. We will discuss the reason later in this chapter.)

There is no longer a way to force a thread to terminate. However, the interrupt method can be used to request termination of a thread. That means that the run method of a thread ought to check once in a while whether it should exit.

public void run()
{
. . .
while (no request to terminate && more work to do)
{
do more work
}
// exit run method and terminate thread
}

However, as you have learned, a thread should not work continuously, but it should go to sleep or wait once in a while, to give other threads a chance to do their work. But when a thread is sleeping, it can't actively check whether it should terminate. This is where the InterruptedException comes in. When the interrupt method is called on a thread object that is currently blocked, the blocking call (such as sleep or wait) is terminated by an InterruptedException.

There is no language requirement that a thread that is interrupted should terminate. Interrupting a thread simply grabs its attention. The interrupted thread can decide how to react to the interruption by placing appropriate actions into the catch clause that deals with the InterruptedException. Some threads are so important that they should simply ignore their interruption by catching the exception and continuing. But quite commonly, a thread will simply want to interpret an interruption as a request for termination. The run method of such a thread has the following form:

public void run()
{
try
{
. . . while (more work to do)
{
do more work
}
}
catch(InterruptedException exception)
{
// thread was interrupted during sleep or wait
}
finally
{
cleanup, if required
}
// exit run method and terminate thread
}

However, there is a problem with this code skeleton. If the interrupt method was called while the thread was not sleeping or waiting, then no InterruptedException was generated. The thread needs to call the interrupted method to find out if it was recently interrupted.

while (!interrupted() && more work to do)
{
do more work
}

In particular, if a thread was blocked while waiting for input/output, the input/output operations are notterminated by the call to interrupt. When the blocking operation has returned, you need to call theinterrupted method to find out if the current thread has been interrupted.

NOTE

Curiously, there are two very similar methods, interrupted and isInterrupted. The interruptedmethod is a static method that checks whether the current thread has been interrupted. (Recall that a thread is interrupted because another thread has called its interrupt method.) Furthermore, calling the interrupted method resets the "interrupted" status of the thread. On the other hand, the isInterrupted method is an instance method that you can use to check whether any thread has been interrupted. Calling it does not change the "interrupted" status of its argument.

It is a bit tedious that there are two distinct ways of dealing with thread interruption—testing the "interrupted" flag and catching the InterruptedException.

It would have been nice if methods such as sleep had been defined to simply return with the "interrupted" flag set when an interruption occurs—then one wouldn't have to deal with theInterruptedException at all. Of course, you can manually set the "interrupted" flag when anInterruptedException is caught:

try
{
sleep(delay);
}
catch (InterruptedException exception)
{
Thread.currentThread().interrupt();
}

You need to use this approach if the sleep method is called from a method that can't throw any exceptions.

NOTE

You'll find lots of published code where the InterruptedException is squelched, like this:

try { sleep(delay); }
catch (InterruptedException exception) {} // DON'T!

Don't do that! Either set the "interrupted" flag of the current thread, or propagate the exception to the calling method (and ultimately to the run method).

If you don't want to clutter up lots of nested methods with isInterrupted tests, you can turn the "interrupted" flag into an exception.

if (isInterrupted()) throw new InterruptedException();

Assuming that your code is already prepared to terminate the run method when anInterruptedException is thrown, this is a painless way of immediately terminating the thread when an interruption is detected. The principal disadvantage is that you have to tag your methods with

throws InterruptedException

since, alas, the InterruptedException is a checked exception.

java.lang.Thread

  • void interrupt() 
    sends an interrupt request to a thread. The "interrupted" status of the thread is set to true. If the thread is currently blocked by a call to sleep or wait, an InterruptedException is thrown.

  • static boolean interrupted() 
    tests whether or not the current thread (that is, the thread that is executing this instruction) has been interrupted. Note that this is a static method. The call has a side effect—it resets the "interrupted" status of the current thread to false.

  • boolean isInterrupted() 
    tests whether or not a thread has been interrupted. Unlike the static interrupted method, this call does not change the "interrupted" status of the thread.

  • static Thread currentThread() 
    returns the Thread object representing the currently executing thread.

Adding Multithreading Capability to Your Java Applications的更多相关文章

  1. End-to-End Tracing of Ajax/Java Applications Using DTrace

    End-to-End Tracing of Ajax/Java Applications Using DTrace         By Amit Hurvitz, July 2007     Aja ...

  2. Gradle Goodness: Running Java Applications from External Dependency

    With Gradle we can execute Java applications using the JavaExec task or the javaexec() method. If we ...

  3. An HTTP & HTTP/2 client for Android and Java applications OkHttp

    HTTP is the way modern applications network. It’s how we exchange data & media. Doing HTTP effic ...

  4. [Java Basics] multi-threading

    1, Process&Threads Most implementations of the Java virtual machine run as a single process. Thr ...

  5. Java性能提示(全)

    http://www.onjava.com/pub/a/onjava/2001/05/30/optimization.htmlComparing the performance of LinkedLi ...

  6. Java Swing interview

    http://www.careerride.com/Swing-AWT-Interview-Questions.aspx   Swing interview questions and answers ...

  7. 115 Java Interview Questions and Answers – The ULTIMATE List--reference

    In this tutorial we will discuss about different types of questions that can be used in a Java inter ...

  8. Java Performance Optimization Tools and Techniques for Turbocharged Apps--reference

    Java Performance Optimization by: Pierre-Hugues Charbonneau reference:http://refcardz.dzone.com/refc ...

  9. Top 25 Most Frequently Asked Interview Core Java Interview Questions And Answers

    We are sharing 25 java interview questions , these questions are frequently asked by the recruiters. ...

随机推荐

  1. 使用Spring 3的@value简化配置文件的读取

    Spring 3支持@value注解的方式获取properties文件中的配置值,大简化了读取配置文件的代码. 1.在applicationContext.xml文件中配置properties文件 & ...

  2. RIA+REST架构实现完美WEB开发

    记得第一次看到REST的身影,是在InfoQ上的一篇介绍,随后又翻阅了后面的参考文章和Developerwork上一些资料,甚至随手翻了翻Roy博士的论文.所幸,在不少人还在体会REST到底是何方神圣 ...

  3. 利用COPYDATASTRUCT传递命令行参数给驻留内存的进程(SendMessage应用)

    我们知道Window进程之间通过API的SendMessage方法传递消息.但是方法参数lParam是Long型,那么如果传递一个字符串(譬如命令行参数)应该怎么办呢,甚至一个对象.结构呢.VB的发送 ...

  4. input框内默认文字点击消失

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  5. 创建Web API

    引言 在公司中用到的都是webAPI的应用程序,这个东西之前没有接触过.但是这个并不是什么新鲜的东西,因我们 之前有mvc的基础,所以说学习这个东西还是比较容易的,在开始的时候自己可能突然蒙圈了.因为 ...

  6. Oracle查看和修改其最大的游标数

    原文 Oracle查看和修改其最大的游标数 以下的文章主要是介绍Oracle查看和修改其最大的游标数,本文主要是通过相关代码的方式来引出Oracle查看和修改其最大的游标数的实际操作步骤,以下就是文章 ...

  7. 锁之“轻量级锁”原理详解(Lightweight Locking)

    大家知道,Java的多线程安全是基于Lock机制实现的,而Lock的性能往往不如人意. 原因是,monitorenter与monitorexit这两个控制多线程同步的bytecode原语,是JVM依赖 ...

  8. C++ STL编程轻松入门基础

    C++ STL编程轻松入门基础 1 初识STL:解答一些疑问 1.1 一个最关心的问题:什么是STL 1.2 追根溯源:STL的历史 1.3 千丝万缕的联系 1.4 STL的不同实现版本 2 牛刀小试 ...

  9. selenium python (十五)控制滚动条操作

    #!/usr/bin/python# -*- coding: utf-8 -*-__author__ = 'zuoanvip' #一般用到操作滚动条的两个场景    #注册时的法律条文的阅读,判断用户 ...

  10. kinect 录制彩色和深度视频

    安装 KinectSDK-v1.8-Setup.exe OpenNI-Windows-x86-2.1.0.msi Qt工程 拷贝 Redist 下内容到 编译的exe所在目录 #include < ...