- 浏览: 240009 次
- 性别:
- 来自: 武汉
最新评论
-
白天看黑夜:
Apache Mina Server 2.0 中文参考手册(带 ...
Apache Mina Server 2.0 中文参考手册 网上有PDF -
zerozone2011:
2017-01-04 17:05:26 Diet handle ...
JAVA多线程设计模式三 Guarded Suspension Pattern -
cuisuqiang:
<!-- 上面3个 import 为导入 CXF 的 ...
Apache CXF 与 Spring 整合简单例子 -
anmo_china:
还有一种方法就是将新版本的jar包引入到工程中,这样最简单
cxf2.4.3中jaxb-api.jar、jaxws-api.jar与jdk1.6.0_02不兼容问题 -
sendreams:
demo级的应用没什么问题,一部署到系统中,就可能会出异常。专 ...
Apache CXF 与 Spring 整合简单例子
Java Thread.interrupt 害人! 中断JAVA线程
http://www.blogjava.net/jinfeng_wang/archive/2008/04/27/196477.html
程序是很简易的。然而,在编程人员面前,多线程呈现出了一组新的难题,如果没有被恰当的解决,将导致意外的行为以及细微的、难以发现的错误。 |
一些轻率的家伙可能被另一种方法Thread.interrupt所迷惑。尽管,其名称似乎在暗示着什么,然而,这种方法并不会中断一个正在运行 的线程(待会将进一步说明),正如Listing A中描述的那样。它创建了一个线程,并且试图使用Thread.interrupt方法停止该线程。 Thread.sleep()方法的调用,为线程的初始化和中止提供了充裕的时间。线程本身并不参与任何有用的操作。 class Example1 extends Thread { boolean stop=false; public static void main( String args[] ) throws Exception { Example1 thread = new Example1(); System.out.println( "Starting thread..." ); thread.start(); Thread.sleep( 3000 ); System.out.println( "Interrupting thread..." ); thread.interrupt(); Thread.sleep( 3000 ); System.out.println("Stopping application..." ); //System.exit(0); } public void run() { while(!stop){ System.out.println( "Thread is running..." ); long time = System.currentTimeMillis(); while((System.currentTimeMillis()-time < 1000)) { } } System.out.println("Thread exiting under request..." ); } } 如果你运行了Listing A中的代码,你将在控制台看到以下输出: |
============================================
Writing multithreaded programs in Java, with its built-in support for
threads, is fairly straightforward. However, multithreading presents a
whole set of new challenges to the programmer that, if not correctly
addressed, can lead to unexpected behavior and subtle, hard-to-find
errors. In this article, we address one of those challenges: how to
interrupt a running thread.
Background
Interrupting a thread means stopping what it is doing before it has
completed its task, effectively aborting its current operation. Whether
the thread dies, waits for new tasks, or goes on to the next step
depends on the application.
Although it may seem simple at first, you must take some precautions in
order to achieve the desired result. There are some caveats you must be
aware of as well.
First of all, forget the Thread.stop
method. Although it indeed stops a running thread, the method is unsafe and was deprecated
, which means it may not be available in future versions of the Java.
Another method that can be confusing for the unadvised is Thread.interrupt
. Despite what its name may imply, the method does not interrupt a running thread (more on this later), as Listing A
demonstrates. It creates a thread and tries to stop it using Thread.interrupt
. The calls to Thread.sleep
(
)
give plenty of time for the thread initialization and termination. The thread itself does not do anything useful.
If you run the code in Listing A, you should see something like this on your console:
Starting thread...
Thread is running...
Thread is running...
Thread is running...
Interrupting thread...
Thread is running...
Thread is running...
Thread is running...
Stopping application...
Even after Thread.interrupt
()
is called, the thread continues to run for a while.
Really interrupting a thread
The best, recommended way to interrupt a thread is to use a shared
variable to signal that it must stop what it is doing. The thread must
check the variable periodically, especially during lengthy operations,
and terminate its task in an orderly manner. Listing B
demonstrates this technique.
Running the code in Listing B will generate output like this (notice how the thread exits in an orderly fashion):
Starting thread...
Thread is running...
Thread is running...
Thread is running...
Asking thread to stop...
Thread exiting under request...
Stopping application...
Although this method requires some coding, it is not difficult to
implement and give the thread the opportunity to do any cleanup needed,
which is an absolute requirement for any multithreaded application. Just
be sure to declare the shared variable as volatile
or enclose any access to it into synchronized
blocks/methods.
So far, so good! But what happens if the thread is blocked waiting for
some event? Of course, if the thread is blocked, it can't check the
shared variable and can't stop. There are plenty of situations when that
may occur, such as calling Object.wait
()
, ServerSocket.accept
()
, and DatagramSocket.receive
()
, to name a few.
They all can block the thread forever. Even if a timeout is employed, it
may not be feasible or desirable to wait until the timeout expires, so a
mechanism to prematurely exit the blocked state must be used.
Unfortunately there is no such mechanism that works for all cases, but
the particular technique to use depends on each situation. In the
following sections, I'll give solutions for the most common cases.
Interrupting a thread with Thread.interrupt
()
As demonstrated in Listing A, the method Thread.interrupt
()
does not interrupt a running thread. What the method actually does is
to throw an interrupt if the thread is blocked, so that it exits the
blocked state. More precisely, if the thread is blocked at one of the
methods Object.wait
, Thread.join
, or Thread.sleep
, it receives an InterruptedException
, thus terminating the blocking method prematurely.
So, if a thread blocks in one of the aforementioned methods, the correct
way to stop it is to set the shared variable and then call the interrupt()
method on it (notice that it is important to set the variable first). If the thread is not blocked, calling interrupt(
)
will not hurt; otherwise, the thread will get an exception (the thread
must be prepared to handle this condition) and escape the blocked state.
In either case, eventually the thread will test the shared variable and
stop. Listing C
is a simple example that demonstrates this technique.
As soon as Thread.interrupt
()
is called in Listing C,
the thread gets an exception so that it escapes the blocked state and
determines that it should stop. Running this code produces output like
this:
Starting thread...
Thread running...
Thread running...
Thread running...
Asking thread to stop...
Thread interrupted...
Thread exiting under request...
Stopping application...
Interrupting an I/O operation
But what happens if the thread is blocked on an I/O operation? I/O can
block a thread for a considerable amount of time, particularly if
network communication is involved. For example, a server may be waiting
for a request, or a network application may be waiting for an answer
from a remote host.
If you're using channels, available with the new I/O API introduced in Java 1.4, the blocked thread will get a ClosedByInterruptException
exception. If that is the case, the logic is the same as that used in the third example—only the exception is different.
But you might be using the traditional I/O available since Java 1.0,
since the new I/O is so recent and requires more work. In this case, Thread.interrupt
()
doesn't help, since the thread will not exit the blocked state. Listing D
demonstrates that behavior. Although the interrupt()
method is called, the thread does not exit the blocked state.
Fortunately, the Java Platform provides a solution for that case by calling the close()
method of the socket the thread is blocked in. In this case, if the
thread is blocked in an I/O operation, the thread will get a SocketException
exception, much like the interrupt()
method causes an InterruptedException
to be thrown.
The only caveat is that a reference to the socket must be available so that its close()
method can be called. That means the socket object must also be shared. Listing E
demonstrates this case. The logic is the same as in the examples presented so far.
And here's the sample output you can expect from running Listing E:
Starting thread...
Waiting for connection...
Asking thread to stop...
accept() failed or interrupted...
Thread exiting under request...
Stopping application...
Multithreading is a powerful tool, but it presents its own set of
challenges. One of these is how to interrupt a running thread. If
properly implemented, these techniques make interrupting a thread no
more difficult than using the built-in operations already provided by
the Java Platform.
相关推荐
Thread.interrupt()方法的使用以及使用它退出线程
Java线程Thread之interrupt中断解析 Java线程Thread之interrupt中断机制是Java多线程编程中的一种重要机制。通过调用Thread.interrupt()方法,可以设置线程的中断状态位,线程会不时地检测这个中断标示位,以判断...
- Thread.getThreadGroup()获取线程所属的线程组,Thread.interrupt()和Thread.currentThread().interrupted()分别用于中断和检查当前线程是否被中断。 10. **线程的等待/通知机制** - 使用wait()、notify()、...
Java提供了丰富的线程控制方法,如`start()`启动线程,`sleep()`使线程暂停一段时间,`join()`让当前线程等待指定线程结束,`yield()`让当前线程让出CPU执行权,以及`interrupt()`中断线程等。 Java还提供了同步...
`sleep()`方法让线程进入堵塞状态,`join()`方法等待线程执行完成,`yield()`方法让当前线程让出CPU,`stop()`方法停止线程(不推荐使用,因为可能引起数据不一致),`interrupt()`方法中断线程,以及`wait()`和`...
### Java线程中断机制详解:`interrupt`与`stop`方法 #### 一、引言 在Java多线程编程中,线程控制是至关重要的技术之一。有时我们需要在特定条件下停止某个线程的执行,或者中断正在等待的线程。Java提供了多种...
9. **线程中断**:通过`interrupt()`方法设置线程的中断标志,线程可以通过检查`isInterrupted()`或`interrupted()`方法来响应中断请求。 10. **线程Local变量**:`ThreadLocal`类为每个线程提供独立的变量副本,...
`javathread.part104.rar`可能是一个关于Java线程深入讲解的压缩包,其中可能包含了系列教程的第104部分。在这个部分,我们可以预见到会涵盖以下几个关键知识点: 1. **线程的基本概念**:线程是程序执行的最小单位...
在IT领域,软中断(Software Interrupt)是一种在操作系统中用于处理特定事件的机制。与硬件中断不同,硬件中断是由外部设备如键盘、鼠标或者网络接口等产生的,而软中断则是由CPU执行的软件指令触发的。软中断在...
线程中断是通过调用`Thread.interrupt()`方法来实现的,它会设置线程的中断标志。当线程正在运行时,这个中断标志通常不会立即导致线程停止,而是作为一种请求,告知线程应该尽快结束。线程需要定期检查中断状态,并...
`javathread.part03.rar`这个压缩包文件很可能包含了关于Java线程深入理解和实践的资源,可能是代码示例、教程文档或者课件。在这个部分,我们将探讨Java线程的一些关键知识点。 1. **线程创建**: Java提供了两种...
`javathread.part04.rar`这个压缩包很可能包含了一部分关于Java线程深入学习的资料,可能涵盖了线程的创建、同步、生命周期管理以及线程池等关键主题。下面将详细阐述这些知识点。 1. **线程的创建**: - **通过...
Java推荐使用更安全的中断机制,即通过`Thread.interrupt()`方法向线程发送中断信号,然后在线程的run方法中定期检查`isInterrupted()`或`interrupted()`状态来优雅地停止线程。这种方式允许线程清理资源并正常退出...
- interrupt():中断线程,线程内部需要处理中断标志来响应中断。 - synchronized:用于控制并发访问共享资源,防止数据不一致。 此外,Java还提供了高级线程管理工具,如: - ExecutorService和ThreadPoolExecutor...
在Java中,线程中断主要通过`Thread.interrupt()`方法实现,这个方法会设置线程的中断状态标志。下面将详细阐述Java线程中断机制的各个方面。 1. **线程中断状态** Java中的线程中断状态是一种标志,由`Thread....
在 Java 中,线程(Thread)类提供了三个相关的方法:interrupt、isInterrupted 和 interrupted,这三个方法都是用于处理线程的中断状态的。下面我们将详细介绍这三个方法的用法和区别。 interrupt 方法 interrupt...
本人利用Thread.Abort()与Thread.Interrupt()可以引起目标线程异常的特点,开发了一种不使用已过时的方法来变相从外部控制线程的挂起与恢复的技术,原理简单,方便理解。 相关技术参考:...
在Java中,线程可以通过`interrupt()`方法中断。当一个线程被中断时,它会抛出`InterruptedException`异常。开发者可以通过检查线程的中断状态来决定是否需要提前终止线程的执行。 ```java public void run() { ...