Thread包含interrupt()方法,因此你可以终止被阻塞的任务,这个方法将设置线程的中断状态。如果一个线程已经被阻塞,或者试图执行一个阻塞操作。那么设置这个线程的中断状态将

抛出InterruptedException。当抛出改异常或者该任务调用Thread.interrupted()时,中断状态将被复位。

  查看Thread的API,关于中断的方法有:

  void interrupt()   interrupts this thread

  static boolean interrupted()  Test whether the current thread has been interrupted

  boolean isInterrupted()  Test whether the current thread has been interrupted

  通过几个例子看一下中断的用法和特点:

  例子一,分别模拟了,中断线程sleep,I/O和synchronized修饰的方法。结论:调用interrupt()方法,只有sleep的线程可以被中断,I/O和用synchronized修饰的线程是不能被中断的

public class Interrupting {
private static ExecutorService service = Executors.newCachedThreadPool(); static void test(Runnable r) throws InterruptedException{
Future<?> f = service.submit(r);
TimeUnit.MILLISECONDS.sleep(100);
System.out.println("Interrupting: " + r.getClass().getName());
f.cancel(true); //interrupts if running
System.out.println("interrupted send to: " + r.getClass().getName()); }
public static void main(String[] args) throws Exception{
// test(new SleepBlocked());
// test(new IOBlocked(System.in));
test(new SynchronizedBlocked());
TimeUnit.SECONDS.sleep(10);
System.out.println("Aborting with System.exit(0)");
System.exit(0);
}
} class SleepBlocked implements Runnable {
@Override
public void run() {
try {
TimeUnit.MILLISECONDS.sleep(100);
} catch (InterruptedException e) {
System.out.println("InterruptedException");
}
System.out.println("Exiting SleepBlocked.run()");
}
} class IOBlocked implements Runnable {
private InputStream is; public IOBlocked(InputStream is) {
this.is = is;
} @Override
public void run() {
try {
System.out.print("waiting for read:");
is.read();
} catch (IOException e) {
if(Thread.currentThread().isInterrupted()) {
System.out.println("Interrupted IO Blocked");
} else {
throw new RuntimeException(e);
}
}
System.out.println("Exiting IOBlocked.run()");
}
} class SynchronizedBlocked implements Runnable {
public SynchronizedBlocked() {
new Thread(){
@Override
public void run() {
f();
}
}.start();
} public synchronized void f() {
while(true) { //Never release lock
Thread.yield();
}
}
@Override
public void run() {
System.out.println("try to call f()");
f();
System.out.println("Exiting SynchronizedBlocked.run()");
}
}

  例子二,sleep是可以被中断的,中断后,中断标识位“复位”

package org.burning.sport.javase.thread.interrupt;

import java.util.concurrent.TimeUnit;

public class InterruptSleep implements Runnable{
@Override
public void run() {
try {
while (true) {
System.out.println("开始睡了");
TimeUnit.SECONDS.sleep(3);
}
} catch (InterruptedException e) {
boolean isInterrupt = Thread.interrupted();
//中断状态被复位
System.out.println("中断状态:" + isInterrupt);
}
} public static void main(String[] args) throws Exception{
Thread t = new Thread(new InterruptSleep());
t.start();
TimeUnit.SECONDS.sleep(5);
t.interrupt();
System.out.println("interrupted is: " + t.isInterrupted());
} }
/*
开始睡了
开始睡了
interrupted is: false
中断状态:false
*/

  例子三,普通方法是中断不了的,并且从最后的输出结果 interrupted is: true 看出中断标识位没有被清除。

package org.burning.sport.javase.thread.interrupt;

import java.util.concurrent.TimeUnit;

public class InterruptCommonTest implements Runnable{
@Override
public void run() {
while (true) {
System.out.println("你中断一个试试");
boolean interrupt = Thread.interrupted();
System.out.println("中断状态" + interrupt);
}
} public static void main(String[] args) throws Exception{
Thread t = new Thread(new InterruptCommonTest());
t.setDaemon(true);
t.start();
TimeUnit.SECONDS.sleep(5);
t.interrupt();
System.out.println("interrupted is: " + t.isInterrupted());
}
}
/*
中断状态false
你中断一个试试
中断状态false
你中断一个试试
中断状态false
interrupted is: true
你中断一个试试
中断状态false
*/

  总结:你能够中断对sleep的调用(或者任何要求抛出InterruptedException的调用)。但是你不能中断正在试图获取synchronized锁或者正在试图执行IO操作的线程

  例子四:Lock与中断的关系。

   上面的例子中看到,synchronized是不能被中断的,但是Lock是可以被中断的。这个算是synchronized和Lock的不同点。查看Lock的API,有一个方法

   void lockInterruptibly() throws InrruptedException 就是可以被中断的方式来获取锁的方法。

package org.burning.sport.javase.thread.interrupt;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock; public class InterruptLockTest implements Runnable{
private static ReentrantLock lock = new ReentrantLock(); @Override
public void run() {
try {
lock.lockInterruptibly();
while(true) {
Thread.yield();
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
} } public static void main(String[] args) throws Exception{
InterruptLockTest lockTest = new InterruptLockTest();
Thread t1 = new Thread(lockTest);
Thread t2 = new Thread(lockTest);
t1.start();
t2.start();
TimeUnit.SECONDS.sleep(3);
t2.interrupt();
System.out.println("结束...");
}
}
/*
结束...
java.lang.InterruptedException
at java.util.concurrent.locks.AbstractQueuedSynchronizer.doAcquireInterruptibly(AbstractQueuedSynchronizer.java:898)
at java.util.concurrent.locks.AbstractQueuedSynchronizer.acquireInterruptibly(AbstractQueuedSynchronizer.java:1222)
at java.util.concurrent.locks.ReentrantLock.lockInterruptibly(ReentrantLock.java:335)
at org.burning.sport.javase.thread.interrupt.InterruptLockTest.run(InterruptLockTest.java:18)
at java.lang.Thread.run(Thread.java:745)
Exception in thread "Thread-1" java.lang.IllegalMonitorStateException
at java.util.concurrent.locks.ReentrantLock$Sync.tryRelease(ReentrantLock.java:151)
at java.util.concurrent.locks.AbstractQueuedSynchronizer.release(AbstractQueuedSynchronizer.java:1261)
at java.util.concurrent.locks.ReentrantLock.unlock(ReentrantLock.java:457)
at org.burning.sport.javase.thread.interrupt.InterruptLockTest.run(InterruptLockTest.java:25)
at java.lang.Thread.run(Thread.java:745)
*/

  

https://gitee.com/play-happy/base-project

参考:

  【1】《Think in Java》,21.3.4 中断

  【2】《Java 高并发程序设计》,2.2.3 线程中断

线程的中断(Lock与synchronized)的更多相关文章

  1. (转)Lock和synchronized比较详解

    今天看了并发实践这本书的ReentantLock这章,感觉对ReentantLock还是不够熟悉,有许多疑问,所有在网上找了很多文章看了一下,总体说的不够详细,重点和焦点问题没有谈到,但这篇文章相当不 ...

  2. Lock较synchronized多出的特性

    1.尝试非阻塞形式获取锁 tryLock() :当前线程尝试获取锁,如果锁被占用返回false;如果成功则占有锁 //类似用法if(lock.tryLock()) { try { System.out ...

  3. Lock和synchronized的区别和使用

    Java并发编程:Lock 今天看了并发实践这本书的ReentantLock这章,感觉对ReentantLock还是不够熟悉,有许多疑问,所有在网上找了很多文章看了一下,总体说的不够详细,重点和焦点问 ...

  4. synchronized和lock以及synchronized和volatile的区别

    synchronized和volatile区别synochronizd和volatile关键字区别: 1. volatile关键字解决的是变量在多个线程之间的可见性:而sychronized关键字解决 ...

  5. java多线程关键字volatile、lock、synchronized

    --------------------- 本文来自 旭日Follow_24 的CSDN 博客 ,全文地址请点击:https://blog.csdn.net/xuri24/article/detail ...

  6. Lock、synchronized和ReadWriteLock,StampedLock戳锁的区别和联系以及Condition

    https://www.cnblogs.com/RunForLove/p/5543545.html 先来看一段代码,实现如下打印效果: 1 2 A 3 4 B 5 6 C 7 8 D 9 10 E 1 ...

  7. Java并发编程:Lock和Synchronized <转>

    在上一篇文章中我们讲到了如何使用关键字synchronized来实现同步访问.本文我们继续来探讨这个问题,从Java 5之后,在java.util.concurrent.locks包下提供了另外一种方 ...

  8. Lock 和 synchronized 的区别

    Lock 和 synchronized 的区别 Lock是一个接口,而synchronized是Java中的关键字,synchronized是内置的语言实现: synchronized在发生异常时,会 ...

  9. 002 Lock和synchronized的区别和使用

    转自 https://www.cnblogs.com/baizhanshi/p/6419268.html 今天看了并发实践这本书的ReentantLock这章,感觉对ReentantLock还是不够熟 ...

随机推荐

  1. jsp中<c:if>标签的用法

    <c:if test="${(tbl.column1 eq '值') and (tbl.column2 eq 'str')}"> <table>...< ...

  2. echarts仪表盘

    echarts链接:https://gallery.echartsjs.com/editor.html?c=xkasbcOqh0 代码: var axislineColor = new echarts ...

  3. project1

    知识漏洞  有空就默写一下-.- [概念] 要好好理解并且背下来记住 MVC要分开,Servlet里面不处理计算的逻辑,只有调用函数(是不是变量传进来以后,调用都不能有呢?) clear map不能直 ...

  4. java_24 FileOutputStream类和FileInputStream类

    1.OutputStream 和InputStream 输入和输出:1.参照物都是java程序来惨遭 2.Input输入,持久化上的数据---->内存 3.Output输出,内存--->硬 ...

  5. 【转载】SQL Server - 使用 Merge 语句实现表数据之间的对比同步

    原文地址:SQL Server - 使用 Merge 语句实现表数据之间的对比同步 表数据之间的同步有很多种实现方式,比如删除然后重新 INSERT,或者写一些其它的分支条件判断再加以 INSERT ...

  6. 更改angular的默认端口

    一.现象 当本地同时运行了多个angular项目时,端口占用问题 Port 4200 is already in use. Use '--port' to specify a different po ...

  7. c++ stl源码剖析学习笔记(三)容器 vector

    stl中容器有很多种 最简单的应该算是vector 一个空间连续的数组 他的构造函数有多个 以其中 template<typename T> vector(size_type n,cons ...

  8. qsort例子

    #include<stdio.h> #include<stdlib.h> #include<string.h> #include<time.h> typ ...

  9. Alpha 冲刺 (7/10)

    队名 火箭少男100 组长博客 林燊大哥 作业博客 Alpha 冲鸭鸭鸭鸭鸭鸭鸭! 成员冲刺阶段情况 林燊(组长) 过去两天完成了哪些任务 协调各成员之间的工作 学习MSI.CUDA 试运行软件并调试 ...

  10. P3258 [JLOI2014]松鼠的新家 (简单的点差分)

    https://www.luogu.org/problemnew/show/P3258 注意开始和最后结尾 #include <bits/stdc++.h> #define read re ...