Javalinux线程同步机制中断机制是怎么回事

本文记录JAVA多线程中的中断机制的一些知识点。主要是stop方法、interrupted()与isInterrupted()方法的区别,并从源代码的实现上进行简单分析。
JAVA中有3种方式可以终止正在运行的线程
①线程正常退出,即run()方法执行完毕了
②使用Thread类中的stop()方法强行终止线程。但stop()方法已经过期了,不推荐使用
③使用中断机制
线程正常退出没有什么东东,中断机制下面详细介绍,先看下stop()方法的源代码,关键是源代码上的注释。它解释了为什么stop()不安全,stop()方法停止的是哪个线程?
* Forces the thread to stop executing.
* If there is a security manager installed, its &code&checkAccess&/code&
* method is called with &code&this&/code&
* as its argument. This may result in a
* &code&SecurityException&/code& being raised (in the current thread).
* If this thread is different from the current thread (that is, the current
* thread is trying to stop a thread other than itself), the
* security manager's &code&checkPermission&/code& method (with a
* &code&RuntimePermission("stopThread")&/code& argument) is called in
* addition.
* Again, this may result in throwing a
* &code&SecurityException&/code& (in the current thread).
* The thread represented by this thread is forced to stop whatever
* it is doing abnormally and to throw a newly created
* &code&ThreadDeath&/code& object as an exception.
* It is permitted to stop a thread that has not yet been started.
* If the thread is eventually started, it immediately terminates.
* An application should not normally try to catch
* &code&ThreadDeath&/code& unless it must do some extraordinary
* cleanup operation (note that the throwing of
* &code&ThreadDeath&/code& causes &code&finally&/code& clauses of
* &code&try&/code& statements to be executed before the thread
* officially dies).
If a &code&catch&/code& clause catches a
* &code&ThreadDeath&/code& object, it is important to rethrow the
* object so that the thread actually dies.
* The top-level error handler that reacts to otherwise uncaught
* exceptions does not print out a message or otherwise notify the
* application if the uncaught exception is an instance of
* &code&ThreadDeath&/code&.
* @exception
SecurityException
if the current thread cannot
modify this thread.
#interrupt()
#checkAccess()
ThreadDeath
ThreadGroup#uncaughtException(Thread,Throwable)
SecurityManager#checkAccess(Thread)
SecurityManager#checkPermission
* @deprecated This method is inherently unsafe.
Stopping a thread with
Thread.stop causes it to unlock all of the monitors that it
has locked (as a natural consequence of the unchecked
&code&ThreadDeath&/code& exception propagating up the stack).
any of the objects previously protected by these monitors were in
an inconsistent state, the damaged objects become visible to
other threads, potentially resulting in arbitrary behavior.
uses of &code&stop&/code& should be replaced by code that simply
modifies some variable to indicate that the target thread should
stop running.
The target thread should check this variable
regularly, and return from its run method in an orderly fashion
if the variable indicates that it is to stop running.
target thread waits for long periods (on a condition variable,
for example), the &code&interrupt&/code& method should be used to
interrupt the wait.
For more information, see
&a href="{@docRoot}/../technotes/guides/concurrency/threadPrimitiveDeprecation.html"&Why
are Thread.stop, Thread.suspend and Thread.resume Deprecated?&/a&.
@Deprecated
public final void stop() {
stop(new ThreadDeath());
上面注释,第9行到第16行表明,stop()方法可以停止&其他线程&。执行thread.stop()方法这条语句的线程称为当前线程,而&其他线程&则是 调用thread.stop()方法的对象thread所代表的线程。
public static void main(String[] args) {
MyThread thread = new MyThread...
thread.stop();
在main方法中,当前线程就是main线程。它执行到第4行,想把&其他线程&thread& 给停止。这个其他线程就是MyThread类 new 的thread对象所表示的线程。
第21行至23行表明,可以停止一个尚未started(启动)的线程。它的效果是:当该线程启动后,就立马结束了。
第48行以后的注释,则深刻表明了为什么stop()方法被弃用!为什么它是不安全的。
比如说,threadA线程拥有了监视器,这些监视器负责保护某些临界资源,比如说银行的转账的金额。当正在转账过程中,main线程调用 threadA.stop()方法。结果导致监视器被释放,其保护的资源(转账金额)很可能出现不一致性。比如,A账户减少了100,而B账户却没有增加100
二,中断机制
JAVA中如何正确地使用中断机制的细节太多了。interrupted()方法与 isInterrupted()方法都是反映当前线程的是否处于中断状态的。
①interrupted()
* Tests whether the current thread has been interrupted.
* &i&interrupted status&/i& of the thread is cleared by this method.
* other words, if this method were to be called twice in succession, the
* second call would return false (unless the current thread were
* interrupted again, after the first call had cleared its interrupted
* status and before the second call had examined it).
* &p&A thread interruption ignored because a thread was not alive
* at the time of the interrupt will be reflected by this method
* returning false.
&code&true&/code& if the current thread
&code&false&/code& otherwise.
* @see #isInterrupted()
* @revised 6.0
public static boolean interrupted() {
return currentThread().isInterrupted(true);
从源码的注释中看出,它测试的是当前线程(current thread)的中断状态,且这个方法会清除中断状态。
②isInterrupted()
* Tests whether this thread has been interrupted.
The &i&interrupted
* status&/i& of the thread is unaffected by this method.
* &p&A thread interruption ignored because a thread was not alive
* at the time of the interrupt will be reflected by this method
* returning false.
&code&true&/code& if this thread
&code&false&/code& otherwise.
#interrupted()
* @revised 6.0
public boolean isInterrupted() {
return isInterrupted(false);
从源码注释中可以看出,isInterrupted()方法不会清除中断状态。
③interrupted()方法与 isInterrupted()方法的区别
从源代码可以看出,这两个方法都是调用的isInterrupted(boolean ClearInterrupted),只不过一个带的参数是true,另一个带的参数是false。
* Tests if some Thread has been interrupted.
The interrupted state
* is reset or not based on the value of ClearInterrupted that is
private native boolean isInterrupted(boolean ClearInterrupted);
因此,第一个区别就是,一个会清除中断标识位,另一个不会清除中断标识位。
再分析源码,就可以看出第二个区别在return 语句上:
public static boolean interrupted() {
return currentThread().isInterrupted(true);
/************************/
public boolean isInterrupted() {
return isInterrupted(false);
interrupted()测试的是当前的线程的中断状态。而isInterrupted()测试的是调用该方法的对象所表示的线程。一个是静态方法(它测试的是当前线程的中断状态),一个是实例方法(它测试的是实例对象所表示的线程的中断状态)。
下面用个具体的例子来更进一步地阐明这个区别。
有一个自定义的线程类如下:
1 public class MyThread extends Thread {
public void run() {
super.run();
for (int i = 0; i & 500000; i++) {
System.out.println("i=" + (i + 1));
先看interrupted()方法的示例:
1 public class Run {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
Thread.sleep(1000);
thread.interrupt();
//Thread.currentThread().interrupt();
System.out.println("是否停止1?="+thread.interrupted());//false
System.out.println("是否停止2?="+thread.interrupted());//false main线程没有被中断!!!      //......
第5行启动thread线程,第6行使main线程睡眠1秒钟从而使得thread线程有机会获得CPU执行。
main线程睡眠1s钟后,恢复执行到第7行,请求中断 thread线程。
第9行测试线程是否处于中断状态,这里测试的是哪个线程呢???答案是main线程。因为:
(1)interrupted()测试的是当前的线程的中断状态
(2)main线程执行了第9行语句,故main线程是当前线程
再看isInterrupted()方法的示例:
1 public class Run3 {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
Thread.sleep(1000);
thread.interrupt();
System.out.println("是否停止1?="+thread.isInterrupted());//true
在第8行,是thread对象调用的isInterrupted()方法。因此,测试的是thread对象所代表的线程的中断状态。由于在第7行,main线程请求中断 thread线程,故在第8行的结果为: true
阅读(...) 评论()博客分类:
在学习CountDownLatch的时候非常关心它是如何阻塞线程和唤醒线程的。最后就追踪到了LockSupport。这个类有着wait(),notify()类似的功能,不过更精准。
LockSupport.park(Thread thread),//阻塞thread
LockSupport.unpark(Thread thread) //唤醒thread这两个方法是相对应的,其实这两个方法调用的是Unsafe中对应的方法,而Unsafe是没有开源的,是通过JNI实现的。notify和wait方法的时候也是调用JNI。
问题1: Thread.interrupt()方法和InterruptedException异常的关系?是由interrupt触发产生了InterruptedException异常?
Thread.interrupt()只是在Object.wait() .Object.join(), Object.sleep()几个方法会主动抛出InterruptedException异常。而在其他的的block常见,只是通过设置了Thread的一个标志位信息,需要程序自我进行处理。
问题2:Thread.interrupt()会中断线程什么状态的工作? RUNNING or BLOCKING?
Thread.interrupt设计的目的主要是用于处理线程处于block状态,比如wait(),sleep()状态就是个例子。但可以在程序设计时为支持task cancel,同样可以支持RUNNING状态。比如Object.join()和一些支持interrupt的一些nio channel设计。
问题3: LockSupport.park()和unpark(),与object.wait()和notify()的区别?
面向的主体不一样。LockSuport主要是针对Thread进进行阻塞处理,可以指定阻塞队列的目标对象,每次可以指定具体的线程唤醒。Object.wait()是以对象为纬度,阻塞当前的线程和唤醒单个(随机)或者所有线程。
实现机制不同。虽然LockSuport可以指定monitor的object对象,但和object.wait(),两者的阻塞队列并不交叉。可以看下测试例子。object.notifyAll()不能唤醒LockSupport的阻塞Thread.
问题4: LockSupport能响应Thread.interrupt()事件不?会抛出InterruptedException异常?
LockSupport能响应interrupt事件,但不会抛出InterruptedException异常。
浏览: 4443 次
来自: 杭州
(window.slotbydup=window.slotbydup || []).push({
id: '4773203',
container: s,
size: '200,200',
display: 'inlay-fix'让天下没有难学的技术
线程管理(四)操作线程的中断机制
线程管理(四)操作线程的中断机制
声明:本文是《 》的第一章, 作者: Javier Fernández González 译者:郑玉婷 校对:欧振聪
操作线程的中断机制
在之前的指南里,你学习了如何中断执行线程和如何对Thread对象的中断控制。之前例子中的机制可以很容易中断的线程中使用。但是如果线程实现的是由复杂的算法分成的一些方法,或者它的方法有递归调用,那么我们可以用更好的机制来控制线程中断。为了这个Java提供了InterruptedException异常。当你检测到程序的中断并在run()方法内捕获,你可以抛这个异常。
在这个指南中, 我们将实现的线程会根据给定的名称在文件件和子文件夹里查找文件,这个将展示如何使用InterruptedException异常来控制线程的中断。
指南中的例子是使用Eclipse IDE 来实现的。如果你使用Eclipse 或者其他的IDE,例如NetBeans, 打开并创建一个新的java项目。
怎么做呢…
按照这些步骤来实现下面的例子::
创建一个名为FileSearch的类,并一定要实现Runnable接口。
public class FileSearch implements Runnable {
声明2个为private的属性,一个是为了我们要查找的文件名和另一个是为了初始文件夹。为这个类实现一个构造函数,并初始化这些属性。
private String initP
private String fileN
public FileSearch(String initPath, String fileName) {
this.initPath = initP
this.fileName = fileN
为FileSearch类实现run()方法。 它会检测fileName属性是不是路径,如果它是,就调用processDirectory()方法。这个方法会抛出一个InterruptedException异常,所以我们应该要捕获它。
public void run() {
File file = new File(initPath);
if (file.isDirectory()) {
directoryProcess(file);
} catch (InterruptedException e) {
System.out.printf(&%s: The search has been interrupted&,Thread.currentThread().getName());
实现 directoryProcess()方法。这个方法会获取文件夹的文件和子文件夹并处理他们。对于每个路径,这个方法会传递路径作为参数来循环调用。对于每个文件,它会调用fileProcess()方法。处理完全部的文件和文件夹后,它会检查线程有没有被中断,在这个例子,会抛出一个InterruptedException异常。
private void directoryProcess(File file) throws
InterruptedException {
File list[] = file.listFiles();
if (list != null) {
for (int i = 0; i & list. i++) {
if (list[i].isDirectory()) {
directoryProcess(list[i]);
fileProcess(list[i]);
if (Thread.interrupted()) {
throw new InterruptedException();
实现 processFile()方法。这方法会比较文件的名字与我们要搜索的文件名。如果他们一样,就写一条信息到控制台。比较完后,线程会检查有没有被中断,在这里,它会抛出一个InterruptedException异常。
private void fileProcess(File file) throws InterruptedException
if (file.getName().equals(fileName)) {
System.out.printf(&%s : %s\n&,Thread.currentThread().getName() ,file.getAbsolutePath());
if (Thread.interrupted()) {
throw new InterruptedException();
现在, 让我们来实现例子的主类吧。实现一个Main类并包含main()方法。
public class Main {
public static void main(String[] args) {
创建并初始一个FileSearch类的对象和一个执行它的任务的线程。然后,开始执行线程。
FileSearch searcher=new FileSearch(&C:\\&,&autoexec.bat&);
Thread thread=new Thread(searcher);
thread.start();
等10秒然后中断线程。
TimeUnit.SECONDS.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
thread.interrupt();
运行例子并查看结果。
它是怎么工作的…
下面的截图给出了例子的执行结果。你可以发现FileSearch对象是如何执行的,当它检测到它被中断时。请看裁图:
在这个例子, 我们使用Java异常来控制线程的中断。当你运行这个例子,程序开始浏览文件夹来检查他们是否含有那个文件。例如,如果你输入\b\c\d,那么程序会循环调用3次processDirectory()方法。当它检测到被中断时,它会抛出InterruptedException异常并继续执行方法,无论已经多少次循环调用。
更多…
InterruptedException 异常是由一些与并发API有关的Java方法,如sleep()抛出的。
第一章,线程管理:线程的中断指南
原创文章,转载请注明: 转载自本文链接地址:
在校学生。电子计算机专业。
Latest posts by 郑玉婷 ()
Related posts:
(5 votes, average: 5.00 out of 5)
Loading...2483人阅读
JavaEE知识体系-------------------(82)
----【Java核心API】(23)
Java中没有提供任何的机制来安全的终止线程,那我们应该怎么让线程停止或者中断呢?
java停止或中断线程有下列方式:
1.调用Thread.stop()
2.利用Thread.interrupt()方法和机制
调用Thread.stop()
使用这种方法强迫停止一个线程,并抛出一个新创建的ThreadDeath对象作为异常,停止一个还未启动的线程也是允许的,如果稍后启动该线程,他会立即终止。一般不应该试图捕获ThreadDeath异常。
但是该方法不安全,已经过时了,我们可以查看JDK API中的介绍:
利用Thread.interrupt()方法和机制
Java中断机制是一种协作机制,意思就是当请求了中断时并不一定直接终止线程,而是需要被中断的线程自己处理中断。
那Java中的中断模型到底是怎么样的呢?
简单理解就是每个线程中都有一个boolean类型的标识,代表着当前是否有中断请求,所有的线程发出中断请求,包括需要被中断的线程自己本身。如果想要发出一个中断请求,只需要在 线程中把需要被中断线程的中断标志设为true就可以了,被中断的线程可以选择适合的时机处理中断请求,也可以不理会中断请求,从而不发生中断。
Thread类中主要下列三个方法中断或者检测中断:
public class ThreadInterruptDemo implements Runnable{
public static void main(String[] args) throws InterruptedException {
Thread thread=new Thread(new ThreadInterruptDemo(),”MyThreadInterruptDemo”);
System.out.println(“……………..start………………”);
thread.start();
Thread.sleep(1000);
System.out.println(“……………..Interrupted………………”);
thread.interrupt();
System.out.println(“线程是否中断”+thread.isInterrupted());
System.out.println(“……………..Stopping………………”);
public void run() {
运行结果为:
可以看出,主线程请求中断后,该线程并没有做处理。
访问:248259次
积分:3836
排名:第9765名
原创:158篇
评论:71条
博文主要参考网上资料,视频笔记,结合个人见解,仅供学习、交流使用,如有侵权,请联系博主删除。
HomePage:&&
JianShu:&&
NowCoder:&&
Address:&&KunMing,China
文章:32篇
阅读:45498
文章:54篇
阅读:55040
文章:84篇
阅读:154413
(24)(3)(8)(3)(2)(6)(9)(11)(12)(16)(9)(22)(15)(18)JAVA多线程之中断机制stop()、interrupted()、isInterrupted()
本文记录JAVA多线程中的中断机制的一些知识点。主要是stop方法、interrupted()与isInterrupted()方法的区别,并从源代码的实现上进行简单分析。
JAVA中有3种方式可以终止正在运行的线程
①线程正常退出,即run()方法执行完毕了
②使用Thread类中的stop()方法强行终止线程。但stop()方法已经过期了,不推荐使用
③使用中断机制
线程正常退出没有什么东东,中断机制下面详细介绍,先看下stop()方法的源代码,关键是源代码上的注释。它解释了为什么stop()不安全,stop()方法停止的是哪个线程?
上面注释,第9行到第16行表明,stop()方法可以停止&其他线程&。执行thread.stop()方法这条语句的线程称为当前线程,而&其他线程&则是 调用thread.stop()方法的对象thread所代表的线程。
MyThread thread =
在main方法中,当前线程就是main线程。它执行到第4行,想把&其他线程&thread& 给停止。这个其他线程就是MyThread类 new 的thread对象所表示的线程。
第21行至23行表明,可以停止一个尚未started(启动)的线程。它的效果是:当该线程启动后,就立马结束了。
第48行以后的注释,则深刻表明了为什么stop()方法被弃用!为什么它是不安全的。
比如说,threadA线程拥有了监视器,这些监视器负责保护某些临界资源,比如说银行的转账的金额。当正在转账过程中,main线程调用 threadA.stop()方法。结果导致监视器被释放,其保护的资源(转账金额)很可能出现不一致性。比如,A账户减少了100,而B账户却没有增加100
二,中断机制
JAVA中如何正确地使用中断机制的细节太多了。interrupted()方法与 isInterrupted()方法都是反应当前线程的是否处于中断状态的。
①interrupted()
从源码的注释中看出,它测试的是当前线程(current thread)的中断状态,且这个方法会清除中断状态。
②isInterrupted()
从源码注释中可以看出,isInterrupted()方法不会清除中断状态。
③interrupted()方法与 isInterrupted()方法的区别
从源代码可以看出,这两个方法都是调用的isInterrupted(
System.out.println("i=" + (i + 1
先看interrupted()方法的示例:
MyThread thread =
Thread.sleep(1000
System.out.println("是否停止1?="+
System.out.println("是否停止2?="+thread.interrupted());//false main线程没有被中断!!!//......
第5行启动thread线程,第6行使main线程睡眠1秒钟从而使得thread线程有机会获得CPU执行。
main线程睡眠1s钟后,恢复执行到第7行,请求中断 thread线程。
第9行测试线程是否处于中断状态,这里测试的是哪个线程呢???答案是main线程。因为:
(1)interrupted()测试的是当前的线程的中断状态
(2)main线程执行了第9行语句,故main线程是当前线程
再看isInterrupted()方法的示例:
MyThread thread =
Thread.sleep(1000
System.out.println("是否停止1?="+thread.isInterrupted());//true
在第8行,是thread对象调用的isInterrupted()方法。因此,测试的是thread对象所代表的线程的中断状态。由于在第7行,main线程请求中断 thread线程,故在第8行的结果为: true
更多相关文章
文章来给各位介绍一下Java多线程中的wait与notify,notifyall例子,希望文章能给各位朋友带来帮助哦.在Java多线程编程中,wait()的作用的是让当前线程进入阻塞状态,notify()是让当前线程唤醒继续执行.虽然是对线程状态的控制,但它们其实都是Object中的方法,这是因为w ...
Java语言支持多线程,本文我们来详细探讨一下Java多线程原理,后面讲了Java多线程应用 ThreadLocal多线程实例.一.线程和进程的概念现在的操作系统是多任务操作系统.多线程是实现多任务的一种方式.进程是程序的一个动态执行过程,是指一个内存中运行的应用程序,每个进程都有自己独立的一块内存 ...
java多线程以前介绍过很多这类文章了,下面我看了月小升博客写的一篇关于多线程让步yield例子了,下面一聚教程小编就来给各位转过来,希望例子对各位会带一帮助.先看个yield让步的例子 代码如下 package com.javaer. public class YThread imp ...
本文章分享一篇关于Java多线程notify&notifyall的区别 ,有需要的朋友可以参考一下下.当一个线程进入wait之后,就必须等其他线程notify/notifyall,使用notifyall,可以唤醒所有处于wait状态的线程,使其重新进入锁的争夺队列中,而notify只能唤醒一 ...
Lock比传统线程模型中的synchronized方式更加面向对象,与生活中的锁类似,锁本身也应该是一个对象.两个线程执行的代码片段要实现同步互斥的效果,它们必须用同一个Lock对象.读写锁:分为读锁和写锁,多个读锁不互斥,读锁与写锁互斥,这是由jvm自己控制的,你只要上好相应的锁即可.如果你的代码 ...
这次说的是Thread的join方法,以前总是使用他的run和sleep方法,哪两个都是比较清楚的,对于这个join方法,他的主要功能就是,当你在一个方法里面调用其他的线程的时候,如果使用了类似thread1.join(),这样的话,这个调用的线程就开始一直等待thread1这个线程返回,什么时候t ...
前言 Java多线程分类中写了21篇多线程的文章,21篇文章的内容很多,个人认为,学习,内容越多.越杂的知识,越需要进行深刻的总结,这样才能记忆深刻,将知识变成自己的.这篇文章主要是对多线程的问题进行总结的,因此罗列了40个多线程的问题. 这些多线程的问题,有些来源于各大网站.有些来源于自己的思考. ...
1.概念和示例代码
进程是内存中运行的一个应用程序,是操作系统分配资源的最小单位.
线程是进程中的一个执行流程,进程可以执行多个线程,线程总是属于某个进程,进程中的多个线程共享进程中的内存资源.
为了更有效的完成任务和利用CPU资源,需要多线程操作,因而需要多线程编程.Java ...
一.什么是Glob?在编程设计中,Glob是一种模式,它使用通配符来指定文件名.例如:*. ...
每个Linux使用者在安装Linux时 都会遇到这样的困境:在为系统分区 ...
1.用Ubuntu 8.10 alternative CD片开机,按English,按F4 ...
Google周五宣布包括企业版.教育版和政府版在 内的Google Apps将停止支持IE ...
网上用CentOS 安装KVM虚拟机的教程很多,而且都相当麻烦,经过我的实验,总算摸索出1 ...
该版本主要是新版Chrome下的bug修正:修复manifest_version版本修复在 ...
发布日期:7更新日期:9受影响系统:Mozilla F ...
发布日期:1更新日期:7受影响系统:Cisco Pri ...
近来,有不少人咨询我关于VIBE算法的问题,而且对于有些细节问题懵懵懂懂,索要源码类的,考 ...
摘要:将服务器数量缩减到之前的十五分之一,并且降低了服务器CPU的使用率,Iron.io成 ...}

我要回帖

更多关于 线程同步机制 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信