interrupt进程终止

interrupt()源码

    /**
* Interrupts this thread.
*
* <p> Unless the current thread is interrupting itself, which is
* always permitted, the {@link #checkAccess() checkAccess} method
* of this thread is invoked, which may cause a {@link
* SecurityException} to be thrown.
*
* <p> If this thread is blocked in an invocation of the {@link
* Object#wait() wait()}, {@link Object#wait(long) wait(long)}, or {@link
* Object#wait(long, int) wait(long, int)} methods of the {@link Object}
* class, or of the {@link #join()}, {@link #join(long)}, {@link
* #join(long, int)}, {@link #sleep(long)}, or {@link #sleep(long, int)},
* methods of this class, then its interrupt status will be cleared and it
* will receive an {@link InterruptedException}.
*
* <p> If this thread is blocked in an I/O operation upon an {@link
* java.nio.channels.InterruptibleChannel InterruptibleChannel}
* then the channel will be closed, the thread's interrupt
* status will be set, and the thread will receive a {@link
* java.nio.channels.ClosedByInterruptException}.
*
* <p> If this thread is blocked in a {@link java.nio.channels.Selector}
* then the thread's interrupt status will be set and it will return
* immediately from the selection operation, possibly with a non-zero
* value, just as if the selector's {@link
* java.nio.channels.Selector#wakeup wakeup} method were invoked.
*
* <p> If none of the previous conditions hold then this thread's interrupt
* status will be set. </p>
*
* <p> Interrupting a thread that is not alive need not have any effect.
*
* @throws SecurityException
* if the current thread cannot modify this thread
*
* @revised 6.0
* @spec JSR-51
*/
public void interrupt() {
if (this != Thread.currentThread())
checkAccess(); synchronized (blockerLock) {
Interruptible b = blocker;
if (b != null) {
interrupt0(); // Just to set the interrupt flag
b.interrupt(this);
return;
}
}
interrupt0();
}

我主要强调一点当线程处于阻塞状态的时候,调用interrupt(),interrupt status 状态会被clear,从true再次变为false。所以对于通过InterruptedException异常

来中断需要正确的try catch语句。

正确的阻塞线程中断方式

package com.java.javabase.thread.base;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class InterruptTest2 { public static void main(String[] args) {
InterruptTest2 test = new InterruptTest2();
Thread t1 = test.new ThreadOne("t1");
t1.start(); try {
Thread.sleep(2000);
t1.interrupt();
log.info("Thread t1 state :{} ", t1.getState());
} catch (InterruptedException e) {
e.printStackTrace();
} } class ThreadOne extends Thread {
public ThreadOne(String name) {
super(name);
} @Override
public void run() {
int i = 0; try {
while (!interrupted()) {
Thread.sleep(500);
log.info("Thread {} state :{} ,run {} times", Thread.currentThread().getName(),
Thread.currentThread().getState(), i++);
}
} catch (InterruptedException e) {
log.info("Thread {} state :{} ,run {} times", Thread.currentThread().getName(),
Thread.currentThread().getState(), i++);
e.printStackTrace();
}
}
}
}

返回结果

2019-07-30 19:52:40,496   [t1] INFO  InterruptTest2  - Thread t1  state :RUNNABLE ,run 0 times
2019-07-30 19:52:41,000 [t1] INFO InterruptTest2 - Thread t1 state :RUNNABLE ,run 1 times
2019-07-30 19:52:41,500 [t1] INFO InterruptTest2 - Thread t1 state :RUNNABLE ,run 2 times
2019-07-30 19:52:41,991 [main] INFO InterruptTest2 - Thread t1 state :TIMED_WAITING
2019-07-30 19:52:41,991 [t1] INFO InterruptTest2 - Thread t1 state :RUNNABLE ,run 3 times
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at com.java.javabase.thread.base.InterruptTest2$ThreadOne.run(InterruptTest2.java:36)

说明

while语句在try catch 捕获到InterruptedException异常,就可以处理。

错误的中断阻塞线程例子

package com.java.javabase.thread.base;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class InterruptTest { public static void main(String[] args) {
InterruptTest test = new InterruptTest();
Thread t1 = test.new ThreadOne("t1");
t1.start(); try {
Thread.sleep(2000);
t1.interrupt();
log.info("Thread state :{} ", t1.getState());
} catch (InterruptedException e) {
e.printStackTrace();
} } class ThreadOne extends Thread {
public ThreadOne(String name) {
super(name);
} @Override
public void run() {
int i = 0;
while (!interrupted()) {
try {
Thread.sleep(500);
log.info("Thread {} state :{} ,run {} times", Thread.currentThread().getName(),
Thread.currentThread().getState(), i++);
} catch (InterruptedException e) {
log.info("Thread {} state :{} ,run {} times", Thread.currentThread().getName(),
Thread.currentThread().getState(), i++);
e.printStackTrace();
}
}
}
}
}

测试结果

2019-07-30 19:54:40,189   [t1] INFO  InterruptTest  - Thread t1  state :RUNNABLE ,run 0 times
2019-07-30 19:54:40,691 [t1] INFO InterruptTest - Thread t1 state :RUNNABLE ,run 1 times
2019-07-30 19:54:41,192 [t1] INFO InterruptTest - Thread t1 state :RUNNABLE ,run 2 times
2019-07-30 19:54:41,686 [t1] INFO InterruptTest - Thread t1 state :RUNNABLE ,run 3 times
2019-07-30 19:54:41,686 [main] INFO InterruptTest - Thread state :TIMED_WAITING
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at com.java.javabase.thread.base.InterruptTest$ThreadOne.run(InterruptTest.java:35)
2019-07-30 19:54:42,187 [t1] INFO InterruptTest - Thread t1 state :RUNNABLE ,run 4 times
2019-07-30 19:54:42,687 [t1] INFO InterruptTest - Thread t1 state :RUNNABLE ,run 5 times
2019-07-30 19:54:43,187 [t1] INFO InterruptTest - Thread t1 state :RUNNABLE ,run 6 times
2019-07-30 19:54:43,687 [t1] INFO InterruptTest - Thread t1 state :RUNNABLE ,run 7 times
2019-07-30 19:54:44,187 [t1] INFO InterruptTest - Thread t1 state :RUNNABLE ,run 8 times
2019-07-30 19:54:44,687 [t1] INFO InterruptTest - Thread t1 state :RUNNABLE ,run 9 times
2019-07-30 19:54:45,187 [t1] INFO InterruptTest - Thread t1 state :RUNNABLE ,run 10 times

错误结果说明

try catch在while语句之内, 捕获到InterruptedException异常,while的!interrupted()会再次返回true

运行态的线程的终止

package com.java.javabase.thread.base;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class InterruptTest3 {
private boolean stopFlag = false; private void stoptask() {
this.stopFlag = true;
} public static void main(String[] args) {
InterruptTest3 test = new InterruptTest3();
Thread t1 = test.new ThreadOne("t1");
t1.start(); try {
Thread.sleep(5000);
test.stoptask();
log.info("Thread t1 state :{} ", t1.getState());
} catch (InterruptedException e) {
e.printStackTrace();
} } class ThreadOne extends Thread {
public ThreadOne(String name) {
super(name);
} int i = 0; @Override
public void run() {
while (!stopFlag) {
try {
sleep(1000);
log.info("Thread {} state :{} ,run {} times", Thread.currentThread().getName(),
Thread.currentThread().getState(), i++);
} catch (InterruptedException e) {
e.printStackTrace();
} }
}
}
}

测试结果

2019-07-30 20:01:19,922   [t1] INFO  InterruptTest3  - Thread t1  state :RUNNABLE ,run 0 times
2019-07-30 20:01:20,923 [t1] INFO InterruptTest3 - Thread t1 state :RUNNABLE ,run 1 times
2019-07-30 20:01:21,923 [t1] INFO InterruptTest3 - Thread t1 state :RUNNABLE ,run 2 times
2019-07-30 20:01:22,923 [t1] INFO InterruptTest3 - Thread t1 state :RUNNABLE ,run 3 times
2019-07-30 20:01:23,918 [main] INFO InterruptTest3 - Thread t1 state :TIMED_WAITING
2019-07-30 20:01:23,923 [t1] INFO InterruptTest3 - Thread t1 state :RUNNABLE ,run 4 times

java并发:interrupt进程终止的更多相关文章

  1. Java并发编程:进程和线程的由来(转)

    Java多线程基础:进程和线程之由来 在前面,已经介绍了Java的基础知识,现在我们来讨论一点稍微难一点的问题:Java并发编程.当然,Java并发编程涉及到很多方面的内容,不是一朝一夕就能够融会贯通 ...

  2. Java 并发:线程中断-interrupt

    一直以为执行了interrupt方法就可以让线程结束,并抛出InterruptedException. 今天看了Java并发编程实战的第七章发现并不是这么回事,在这章的开头就提到 要使任务和线程能安全 ...

  3. Java并发编程:进程和线程之由来

    Java多线程基础:进程和线程之由来 在前面,已经介绍了Java的基础知识,现在我们来讨论一点稍微难一点的问题:Java并发编程.当然,Java并发编程涉及到很多方面的内容,不是一朝一夕就能够融会贯通 ...

  4. java并发编程:进程和线程

    java并发编程涉及到很多内容,当然也包括多线程,再次补充点相关概念 原文地址:http://www.cnblogs.com/dolphin0520/p/3910667.html 一.操作系统中为什么 ...

  5. Java并发编程:进程和线程之由来__进程让操作系统的并发性成为可能,而线程让进程的内部并发成为可能

    转载自海子:http://www.cnblogs.com/dolphin0520/p/3910667.html Java多线程基础:进程和线程之由来 在前面,已经介绍了Java的基础知识,现在我们来讨 ...

  6. Java并发编程:线程和进程的创建(转)

    Java并发编程:如何创建线程? 在前面一篇文章中已经讲述了在进程和线程的由来,今天就来讲一下在Java中如何创建线程,让线程去执行一个子任务.下面先讲述一下Java中的应用程序和进程相关的概念知识, ...

  7. Java并发基础:进程和线程之由来

    转载自:http://www.cnblogs.com/dolphin0520/p/3910667.html 在前面,已经介绍了Java的基础知识,现在我们来讨论一点稍微难一点的问题:Java并发编程. ...

  8. Java并发编程之线程生命周期、守护线程、优先级、关闭和join、sleep、yield、interrupt

    Java并发编程中,其中一个难点是对线程生命周期的理解,和多种线程控制方法.线程沟通方法的灵活运用.这些方法和概念之间彼此联系紧密,共同构成了Java并发编程基石之一. Java线程的生命周期 Jav ...

  9. Java并发编程(一):进程和线程之由来

    转自:http://www.cnblogs.com/dolphin0520/p/3910667.html 在前面,已经介绍了Java的基础知识,现在我们来讨论一点稍微难一点的问题:Java并发编程.当 ...

随机推荐

  1. sort的使用

    sort主要是用来排序的,可以用自定义的函数进行比较,也可以用系统的4中函数进行比较,即less(),greater(),less_equal(),greater_equal().但是我试了一下,发现 ...

  2. Linux 笔记:文件名

    文件名 Linux 系统区分英文字符的大小写.比如,myfile, Myfile 和 myFILE表示的是三个不同的文件.同样,用户密码和登录名也需要区分大小写(这里沿用了Unix 和 C 语言的命名 ...

  3. JDBC 通过读取文件进行初始化

  4. python numpy的var std cov研究

    var:表示方差, 即各项-均值的平方求和后再除以N , std:表示标准差,是var的平方根. cov:协方差 ,与var类似,但是除以(N-1) import numpy as np # 构建测试 ...

  5. 【C#】图解如何添加引用using MySql.Data.MySqlClient;

    使用C#连接MySQL时,经常会用到命名空间using MySql.Data.MySqlClient; 这说明VS中没有添加引用,解决方法如下: 1,可点击以下两个链接的其中任何一个,下载MySQL. ...

  6. 使用YII缓存注意事项

    在使用YII自身缓存时,在main.php文件配置中一定要配置keyPrefix,如下图: 'cache' => array( 'class' => 'CFileCache', 'keyP ...

  7. 【C++初学者自学笔记三】哑元函数、缺省参数、内联函数(模块二,PS:需要用到重载函数)

    一,哑元函数:一个函数的参数只有类型没有名字的则这个参数称之为哑元.类似于void fun(int); 功能:1保持向前的兼容性,比方说我们需要做成一个成品,然后成品是会不断的更新第一代第二代,当我们 ...

  8. Linux进程内消息总线设计

    文章目录 Windows平台进程内消息总线 如果没有消息总线,会产生什么问题 死循环包含关系 高耦合.低内聚 消息总线 结构图 原理 生产者与总线的关系 总线与消费者的关系 Linux进程内消息总线设 ...

  9. AttributeError: 'Word2Vec' object has no attribute 'vocab'

    在 Gensim 1.0.0 版本后移除了 vocab,需使用 model.wv.vocab

  10. python 中的生成器(generator)

    生成器不会吧结果保存在一个系列里,而是保存生成器的状态,在每次进行迭代时返回一个值,直到遇到StopTteration异常结束 1.生成器语法: 生成器表达式:通列表解析语法,只不过把列表解析的[] ...