Adding Multithreading Capability to Your Java Applications
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的更多相关文章
- 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 ...
- 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 ...
- 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 ...
- [Java Basics] multi-threading
1, Process&Threads Most implementations of the Java virtual machine run as a single process. Thr ...
- Java性能提示(全)
http://www.onjava.com/pub/a/onjava/2001/05/30/optimization.htmlComparing the performance of LinkedLi ...
- Java Swing interview
http://www.careerride.com/Swing-AWT-Interview-Questions.aspx Swing interview questions and answers ...
- 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 ...
- Java Performance Optimization Tools and Techniques for Turbocharged Apps--reference
Java Performance Optimization by: Pierre-Hugues Charbonneau reference:http://refcardz.dzone.com/refc ...
- 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. ...
随机推荐
- Ubuntu 安装
最近又有工作需要,又需要在虚拟机上工作了.记得上次使用Ubuntu的时候还是7,8年前呢 用的是vmware 7 ,buntu的版本记不清了.时隔多年又捡起来了,记忆还停留在过去,于是被折腾惨了. 1 ...
- Java 8开发的4大顶级技巧
我使用Java 8编码已经有些年头,既用于新的应用程序,也用来迁移现有的应用,感觉是时候写一些我发现的非常有用的“最佳实践”.我个人并不喜欢“最佳实践”这个说法,因为它意味着“一刀切”的解决方案,而编 ...
- YII Framework学习教程-YII的日志
日志的作用(此处省略1000字) YII中的日志很好很强大,允许你把日志信息存放到数据库,发送到制定email,存放咋文件中,意见显示页面是,甚至可以用来做性能分析. YII中日志的基本配置:/yii ...
- Pig Run on Hadoop, V1.0
——安装hadoop参考这篇blog: http://www.cnblogs.com/lanxuezaipiao/p/3525554.html?__=1a36 后面产生的问题,slave和master ...
- MATLAB Coder从MATLAB生成C/C++代码步骤
MATLAB Coder可以从MATLAB代码生成独立的.可读性强.可移植的C/C++代码. 使用MATLAB Coder产生代码的3个步骤: 准备用于产生代码的MATLAB算法: 检查MATLAB代 ...
- 60个响应式的Web设计教程–能够手机访问!
想要学习响应式[responsive:屏幕自适应的效果]的网页设计和开发技术?在这个超大的收藏集合中,我想你定会找到想要开始学习的响应式网页设计教程. 面对超过1亿的手机互联网用户,开发专业和用户友好 ...
- the NTP socket is in use, exiting
centos下使用如下命令手动同步服务器时间 ntpdate ntp.fudan.edu.cn 或 ntpdate ntp.api.bz 出现“the NTP socket is in use, ex ...
- 用pdo实现的织梦后台留言板
<?php //ini_set("display_errors", "On"); include("data/common.inc.php&qu ...
- 第二百二十天 how can I 坚持
今天如愿去了凤凰岭,比想象中的好多了.山好陡,都没有爬到山顶,下山时山都有点黑了,有点恐怖. 凤凰岭啊.有时间还得再去趟. 下周去八大处.坚持. 看什么时候能把北京这些山爬完,然后 三山五岳. 不爽. ...
- cocos2d-x 3.2 例子文件工程的位置
更新到3.2后突然想要看看官方的例子,忽然发现在test中的cpp工程下面没有了工程的启动配置.奇怪,难道只有代码吗?重新查找后原来启动的工程文件都移动到了build文件夹下面,具体的路径就是 coc ...