1、线程中断机制
什么是中断?
中断只是一种协作机制,Java没有给中断增加任何语法,中断的过程完全需要程序员自己实现。若要中断一个线程,你需要手动调用该线程的interrupt方法,该方法也仅仅是将线程对象的中断标识设成true;接着你需要自己写代码不断地检测当前线程的标识位,如果为true,表示别的线程要求这条线程中断,此时究竟该做什么需要你自己写代码实现。
每个线程对象中都有一个标识,用于表示线程是否被中断;该标识位为true表示中断,为false表示未中断;通过调用线程对象的interrupt方法将该线程的标识位设为true;可以在别的线程中调用,也可以在自己的线程中调用。
2、如何使用中断标识停止线程?
在需要中断的线程中不断监听中断状态,一旦发生中断,就执行相应的中断处理业务逻辑。
2.1、通过一个volatile变量实现
public class InterruptDemo{
public volatile static boolean exit = false;
public static class T extends Thread {
@Override
public void run() {
while (true) {
//循环处理业务
if (exit) {
break;
}
}
}
}
public static void setExit() {
exit = true;
}
public static void main(String[] args) throws InterruptedException {
T t = new T();
t.start();
TimeUnit.SECONDS.sleep(3);
setExit();
}
}
2.2、通过AtomicBoolean
public class StopThreadDemo
{
private final static AtomicBoolean atomicBoolean = new AtomicBoolean(true);
public static void main(String[] args)
{
Thread t1 = new Thread(() -> {
while(atomicBoolean.get())
{
try { TimeUnit.MILLISECONDS.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); }
System.out.println("-----hello");
}
}, "t1");
t1.start();
try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); }
atomicBoolean.set(false);
}
}
2.3、通过Thread类自带的中断API方法实现
2.3.1、中断的相关API方法
方法名 | 方法介绍 |
---|---|
public void interrupt() | 实例方法, 实例方法interrupt()仅仅是设置线程的中断状态为true,不会停止线程 |
public static boolean interrupted() | 静态方法,Thread.interrupted(); 判断线程是否被中断,并清除当前中断状态 这个方法做了两件事: 1、返回当前线程的中断状态 2、将当前线程的中断状态设为false 连续调用两次的结果可能不一样 |
public boolean isInterrupted() | 实例方法, 判断当前线程是否被中断(通过检查中断标志位) |
2.3.2、public void interrupt() 和 public boolean isInterrupted()
public class InterruptDemo
{
public static void main(String[] args)
{
Thread t1 = new Thread(() -> {
while(true)
{
//获取标识符的boolean值
if(Thread.currentThread().isInterrupted())
{
System.out.println("-----t1 线程被中断了,break,程序结束");
break;
}
System.out.println("-----hello");
}
}, "t1");
t1.start();
System.out.println("**************"+t1.isInterrupted());
//暂停5毫秒
try { TimeUnit.MILLISECONDS.sleep(5); } catch (InterruptedException e) { e.printStackTrace(); }
t1.interrupt();//将中断标识修改成true
System.out.println("**************"+t1.isInterrupted());
}
}
2.3.2、public static boolean interrupted()
/**
* 作用是测试当前线程是否被中断(检查中断标志),返回一个boolean并清除中断状态,
* 第二次再调用时中断状态已经被清除,将返回一个false。
*/
public class InterruptDemo
{
public static void main(String[] args) throws InterruptedException
{
System.out.println(Thread.currentThread().getName()+"---"+Thread.interrupted());
System.out.println(Thread.currentThread().getName()+"---"+Thread.interrupted());
System.out.println("111111");
Thread.currentThread().interrupt();
System.out.println("222222");
System.out.println(Thread.currentThread().getName()+"---"+Thread.interrupted());
System.out.println(Thread.currentThread().getName()+"---"+Thread.interrupted());
}
}
3、LockSupport
LockSupport位于java.util.concurrent.locks(简称juc)包中,用于创建锁和其他同步类的基本线程阻塞原语,是juc中一个基础类。
3.1、线程等待唤醒机制
3.1.1、3种让线程等待和唤醒的方法
- 使用Object中的wait()方法让线程等待,使用Object中的notify()方法唤醒线程
- 使用JUC包中Condition的await()方法让线程等待,使用signal()方法唤醒线程
- LockSupport类可以阻塞当前线程以及唤醒指定被阻塞的线程
3.1.2、Object类中的wait和notify方法实现线程等待和唤醒
使用Object中的wait()方法让线程等待,使用Object中的notify()方法唤醒线程。将notify放在wait方法前面,程序无法执行,无法唤醒wait和notify方法,必须要在同步块或者方法里面,且成对出现使用。
/**
*
* 要求:t1线程等待3秒钟,3秒钟后t2线程唤醒t1线程继续工作
*
* 1 正常程序演示
*
* 以下异常情况:
* 2 wait方法和notify方法,两个都去掉同步代码块后看运行效果
* 2.1 异常情况
* Exception in thread "t1" java.lang.IllegalMonitorStateException at java.lang.Object.wait(Native Method)
* Exception in thread "t2" java.lang.IllegalMonitorStateException at java.lang.Object.notify(Native Method)
* 2.2 结论
* Object类中的wait、notify、notifyAll用于线程等待和唤醒的方法,都必须在synchronized内部执行(必须用到关键字synchronized)。
*
* 3 将notify放在wait方法前面
* 3.1 程序一直无法结束
* 3.2 结论
* 先wait后notify、notifyall方法,等待中的线程才会被唤醒,否则无法唤醒
*/
public class LockSupportDemo
{
public static void main(String[] args)//main方法,主线程一切程序入口
{
Object objectLock = new Object(); //同一把锁,类似资源类
new Thread(() -> {
synchronized (objectLock) {
try {
objectLock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+"\t"+"被唤醒了");
},"t1").start();
//暂停几秒钟线程
try { TimeUnit.SECONDS.sleep(3L); } catch (InterruptedException e) { e.printStackTrace(); }
new Thread(() -> {
synchronized (objectLock) {
objectLock.notify();
}
//objectLock.notify();
/*synchronized (objectLock) {
try {
objectLock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}*/
},"t2").start();
}
}
3.1.3、Condition接口中的await后signal方法实现线程的等待和唤醒
使用JUC包中Condition的await()方法让线程等待,使用signal()方法唤醒线程/调用condition中线程等待和唤醒的方法的前提是,要在lock和unlock方法中,要有锁才能调用。
public class LockSupportDemo2
{
public static void main(String[] args)
{
Lock lock = new ReentrantLock();
Condition condition = lock.newCondition();
new Thread(() -> {
lock.lock();
try
{
System.out.println(Thread.currentThread().getName()+"\t"+"start");
condition.await();
System.out.println(Thread.currentThread().getName()+"\t"+"被唤醒");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
},"t1").start();
//暂停几秒钟线程
try { TimeUnit.SECONDS.sleep(3L); } catch (InterruptedException e) { e.printStackTrace(); }
new Thread(() -> {
lock.lock();
try
{
condition.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
System.out.println(Thread.currentThread().getName()+"\t"+"通知了");
},"t2").start();
}
}
3.1.4、LockSupport类中的park等待和unpark唤醒
LockSupport是用来创建锁和其他同步类的基本线程阻塞原语。
LockSupport类使用了一种名为Permit(许可)的概念来做到阻塞和唤醒线程的功能, 每个线程都有一个许可(permit),
permit只有两个值1和零,默认是零。
可以把许可看成是一种(0,1)信号量(Semaphore),但与 Semaphore 不同的是,许可的累加上限是1。
许可证可以先申请、也可以后申请。
public class LockSupportDemo3
{
public static void main(String[] args)
{
//正常使用+不需要锁块
Thread t1 = new Thread(() -> {
System.out.println(Thread.currentThread().getName()+" "+"1111111111111");
LockSupport.park();
System.out.println(Thread.currentThread().getName()+" "+"2222222222222------end被唤醒");
},"t1");
t1.start();
//暂停几秒钟线程
try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); }
LockSupport.unpark(t1);
System.out.println(Thread.currentThread().getName()+" -----LockSupport.unparrk() invoked over");
}
}