bilibili尚硅谷周阳老师JUC并发编程与源码分析课程笔记第四章——LockSupport与线程中断

LockSupport与线程中断

2内容简介

LockSupport

指java.util.concurrent.locks.LockSupport类,功能非常强大!

线程中断机制

指java.lang.Thread类中的三个方法:

public void interrupt();

public static boolean interrupted();

public boolean isInterrupted();

线程中断机制

从阿里蚂蚁金服面试题讲起

java.lang.Thread类中的三个方法:

public void interrupt();

public static boolean interrupted();

public boolean isInterrupted();

这三个方法是什么,用在哪,使用过程中的利弊如何和各自特点?

如何中断一个运行中的线程?

如何停止一个运行中的线程?

什么是中断机制?

首先

一个线程不应该由其他线程来强制中断或停止,而是应该由线程自己自行停止,自己来决定自己的命运,所以Thread.stop,Thread.suspend,Thread.resume都已经被废弃了

其次

在Java中没有办法立即停止一条线程,然而停止线程却显得尤为重要,如取消一个耗时操作。因此,Java提供了一种用于停止线程的协商机制——中断,也即中断标识协商机制

中断只是一种协作协商机制,Java没有给中断增加任何语法,中断的过程完全需要程序员自行实现。若要中断一个线程,你需要手动调用该线程interrupt方法,该方法也仅仅是将该线程对象的中断标识设置为true,接着你需要自己写代码不断检测当前线程的标识位,如果为true,表示别的线程请求这条线程中断,此时究竟应该做什么需要你自己写代码实现

每个线程对象都有一个中断标识位,用于表示线程是否被中断;该标识位为true表示中断,为false表示未中断;通过调用线程对象的interrupt方法将该线程的标识位设置为true;可以在别的线程中调用,也可以在自己的线程中调用

中断的相关API方法之三大方法说明

  • public void interrupt()

    • 实例方法, Just to set the interrupt flag
    • 实例方法interrupt()仅仅是设置线程的中断状态为true,发起一个协商而不会立刻停止线程
  • public static boolean interrupted()

    • 静态方法,Thread.interrupted();
    • 判断线程是否被中断并清除当前中断状态(做了两件事情)
      • 1.返回当前线程的中断状态,测试当前线程是否已被中断
      • 2.将当前线程的中断状态清零并重新设置为false,清除线程的中断状态
    • 这个方法有点不好理解在于如果连续两次调用此方法,则第二次返回false,因为连续调用两次的结果可能不一样
  • public boolean isInterrupted()

    • 实例方法
    • 判断当前线程是否被中断(通过检查中断标识位)

大厂面试题中断机制考点

如何停止中断运行中的线程?
通过一个volatile变量实现
package com.bilibili.juc.interrupt;

import java.util.concurrent.TimeUnit;

public class InterruptDemo {

    static volatile boolean isStop = false; // volatile修饰的变量具有可见性

    public static void main(String[] args) {
        new Thread(() -> {
            while (true) {
                if (isStop) {
                    System.out.println(Thread.currentThread().getName() + "\t isStop的值被改为true,程序停止");
                    break;
                }
                System.out.println(Thread.currentThread().getName() + "--------hello volatile--------");
            }
        }, "t1").start();
      
        try {
            TimeUnit.MILLISECONDS.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(() -> isStop = true, "t2").start();
    }

}

输出结果:
t1--------hello volatile--------
t1--------hello volatile--------
t1--------hello volatile--------
t1--------hello volatile--------
...
t1--------hello volatile--------
t1--------hello volatile--------
t1--------hello volatile--------
t1--------hello volatile--------
t1	 isStop的值被改为true,程序停止
通过AutomicBoolean
package com.bilibili.juc.interrupt;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

public class InterruptDemo2 {

    static AtomicBoolean atomicBoolean = new AtomicBoolean(false);

    public static void main(String[] args) {
        new Thread(() -> {
            while (true) {
                if (atomicBoolean.get()) {
                    System.out.println(Thread.currentThread().getName() + "\t atomicBoolean的值被改为true,程序停止");
                    break;
                }
                System.out.println(Thread.currentThread().getName() + "--------hello atomicBoolean--------");
            }
        }, "t1").start();

        try {
            TimeUnit.MILLISECONDS.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(() -> atomicBoolean.set(true), "t2").start();
    }

}

输出结果:
t1--------hello atomicBoolean--------
t1--------hello atomicBoolean--------
t1--------hello atomicBoolean--------
t1--------hello atomicBoolean--------
...
t1--------hello atomicBoolean--------
t1--------hello atomicBoolean--------
t1--------hello atomicBoolean--------
t1--------hello atomicBoolean--------
t1	 atomicBoolean的值被改为true,程序停止
通过Thread类自带的中断API实例方法实现

在需要中断的线程中不断监听中断状态,一旦发生中断,就执行相应的中断处理业务逻辑stop线程。

package com.bilibili.juc.interrupt;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

public class InterruptDemo3 {

    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            while (true) {
                if (Thread.currentThread().isInterrupted()) {
                    System.out.println(Thread.currentThread().getName() + "\t isInterrupted的值被改为true,程序停止");
                    break;
                }
                System.out.println(Thread.currentThread().getName() + "--------hello interrupt api--------");
            }
        }, "t1");
        t1.start();
      
        System.out.println("--------t1的默认中断标识位:" + t1.isInterrupted());
      
        try {
            TimeUnit.MILLISECONDS.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(t1::interrupt, "t2").start(); // t2向t1发出协商,将t1线程的中断状态为true
//        t1.interrupt(); // 也可以自己调用interrupt()方法将自己线程的中断状态为true
    }

}

输出结果:
--------t1的默认中断标识位:false
t1--------hello interrupt api--------
t1--------hello interrupt api--------
t1--------hello interrupt api--------
t1--------hello interrupt api--------
...
t1--------hello interrupt api--------
t1--------hello interrupt api--------
t1--------hello interrupt api--------
t1--------hello interrupt api--------
t1	 isInterrupted的值被改为true,程序停止
interrupt()方法源码分析
/**
中断此线程
除非当前线程正在中断(始终允许),否则将调用此线程的checkAccess方法,这可能会导致抛出SecurityException
如果该线程阻塞的调用Object类的wait(),wait(long)或wait(long, int)方法,或Thread类的join(),join(long),join(long, int),sleep(long),或sleep(long, int)方法,那么它的中断状态将被清除,并目将收到InterruptedException
如果在InterruptibleChannel上的I/O操作中阻止该丝程,则通道将关闭,线程的中断状态将被设置,线程将收到ClosedByInterruptException
如果该线程在Selector中被阻塞,则线程的中断状态将被设置,它将立即从选择操作返回,可能具有非零值,就像调用选择器的wakeup方法一样。
如果以前的条件都不成立,则将设置该线程的中断状态。
中断不活动的线程不会产生任何影响。
异常:SecurityException —— 如果当前线程无法修改此线程
 */
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();
}

private native void interrupt0(); // 本地方法
isInterrupted()方法源码分析
/**
测试此线程是否已中断
线程的interrupted状态不受此方法影响
返回true代表此线程已经被中断,false则此线程未被中断
 */
public boolean isInterrupted() {
    return isInterrupted(false);
}

/**
测试某些线程是否已中断。中断状态是否复位取决于传递的ClearInterrupted的值
 */
private native boolean isInterrupted(boolean ClearInterrupted); // 本地方法
小总结

具体来说,当一个线程调用interrupt()方法时:

  1. 如果线程处于正常活动状态,那么会将该线程的中断标识设置为true,仅此而已
    • 被设置中断标识的线程将继续运行,不受影响
    • 所以,interrupt()方法并不能真正的中断线程,需要被调用的线程自己进行配合才行
  2. 如果线程处于被阻塞状态(例如处于sleep、wait、join等状态),在别的线程中调用当前线程对象的interrupt()方法,那么线程将立即退出被阻塞状态,并抛出一个InterruptedException异常
当前线程的中断标识为true,是不是线程就立刻停止?

答案是不立刻停止,实例方法interrupt()仅仅是设置线程的中断状态位为true,不会停止线程

Code
package com.bilibili.juc.interrupt;

import java.util.concurrent.TimeUnit;

public class InterruptDemo4 {

    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            for (int i = 1; i <= 300; i++) {
                System.out.println("--------: " + i);
            }
            System.out.println("t1线程调用interrupt()后的中断标识位02:" + Thread.currentThread().isInterrupted());
        }, "t1");
        t1.start();

        System.out.println("t1线程默认的中断标识位:" + t1.isInterrupted()); // false

        try {
            TimeUnit.MILLISECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        t1.interrupt(); // 设置t1线程的中断标识位为true
        
        System.out.println("t1线程调用interrupt()后的中断标识位01:" + t1.isInterrupted()); // true

        try {
            TimeUnit.MILLISECONDS.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // 2000毫秒后,t1线程已经不活动了,不会产生任何影响
        System.out.println("t1线程调用interrupt()后的中断标识位03:" + t1.isInterrupted()); // false
    }

}

输出结果:
t1线程默认的中断标识位:false
--------: 1
--------: 2
--------: 3
--------: 4
...
--------: 90
--------: 91
--------: 92
--------: 93
t1线程调用interrupt()后的中断标识位01true
--------: 94
--------: 95
--------: 96
--------: 97
...
--------: 297
--------: 298
--------: 299
--------: 300
t1线程调用interrupt()后的中断标识位02true
t1线程调用interrupt()后的中断标识位03false

Code后手案例(重要,面试就是它,操蛋)
/**
 * @author Guanghao Wei
 * @create 2023-04-11 11:23
 *1. 中断标志位默认为false
 * 2.t2对t1发出中断协商  t1.interrupt();
 * 3. 中断标志位为true: 正常情况 程序停止
 *     中断标志位为true  异常情况,.InterruptedException ,将会把中断状态清楚,中断标志位为false
 * 4。需要在catch块中,再次调用interrupt()方法将中断标志位设置为false;
 */
package com.bilibili.juc.interrupt;

import java.util.concurrent.TimeUnit;

/**
 * @ClassName: InterruptDemo5
 * @Description:
 * @Author: zhangjin
 * @Date: 2023/10/20
 */
public class InterruptDemo5 {

    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            while (true) {
                if (Thread.currentThread().isInterrupted()) {
                    System.out.println(Thread.currentThread().getName() + "\t中断标志位为:" + Thread.currentThread().isInterrupted() + "\t程序停止");
                    break;
                }
                // sleep方法抛出InterruptedException后,中断标识也被清空置为false,如果没有在
                // catch方法中调用interrupt方法再次将中断标识置为true,这将导致无限循环了
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    // Thread.currentThread().interrupt();
                    e.printStackTrace();
                }
                System.out.println("--------hello InterruptDemo5--------");

            }
        }, "t1");
        t1.start();

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(() -> t1.interrupt(), "t2").start();
    }

}

输出结果:
--------hello InterruptDemo5--------
--------hello InterruptDemo5--------
--------hello InterruptDemo5--------
--------hello InterruptDemo5--------
java.lang.InterruptedException: sleep interrupted
	at java.lang.Thread.sleep(Native Method)
	at com.bilibili.juc.interrupt.InterruptDemo5.lambda$main$0(InterruptDemo5.java:23)
	at java.lang.Thread.run(Thread.java:748)
--------hello InterruptDemo5--------
--------hello InterruptDemo5--------
--------hello InterruptDemo5--------
--------hello InterruptDemo5--------
... // 程序未停止

提出疑问:为什么程序未停止,产生了死循环?

解决:放开注释Thread.currentThread().interrupt();这段代码,得到输出结果

--------hello InterruptDemo5--------
--------hello InterruptDemo5--------
--------hello InterruptDemo5--------
--------hello InterruptDemo5--------
--------hello InterruptDemo5--------
--------hello InterruptDemo5--------
t1	中断标志位为:true	程序停止
java.lang.InterruptedException: sleep interrupted
	at java.lang.Thread.sleep(Native Method)
	at com.bilibili.juc.interrupt.InterruptDemo5.lambda$main$0(InterruptDemo5.java:23)
	at java.lang.Thread.run(Thread.java:748)

分析:

  1. 中断标志位,默认为false
  2. t2对t1发出中断协商,t2调用t1.interrupt(),中断标志位设置为true
  3. 中断标志位为true:正常情况,程序停止
  4. 中断标志位为true:异常情况,InterruptedException ,将会把中断状态清除,并收到InterruptedException,中断标志位为false,此时导致无限循环
  5. 需要在catch块中,再次调用interrupt()方法将中断标志位设置为true,二次调用停止程序
    ps:具体也可以见之前interrupt()方法源码分析
小总结

中断只是一种协商机制,修改中断标识位仅此而已,不是立刻stop打断

sleep方法抛出InterruptedException后,中断标识也被清空置为false,如果没有在catch方法中调用interrupt方法再次将中断标识置为true,这将导致无限循环了

静态方法Thread.interrupted(),谈谈你的理解?
interrupted()方法源码分析
/**
测试当前线程是否已中断。该方法清除线程的中断状态。换句话说,如果这个方法被连续调用两次,第二次调用将返回false(除非当前线程再次被中断,在第一次调用清除了中断状态之后,在第二次调用检查它之前)
返回true代表此线程已经被中断,false则此线程未被中断
 */
public static boolean interrupted() {
    return currentThread().isInterrupted(true);
}

/**
测试某些线程是否已中断。中断状态是否复位取决于传递的ClearInterrupted的值
*/
private native boolean isInterrupted(boolean ClearInterrupted);
Code
package com.bilibili.juc.interrupt;

public class InterruptDemo6 {

    public static void main(String[] args) {
        System.out.println(Thread.currentThread().getName() + "\t" + Thread.interrupted());
        System.out.println(Thread.currentThread().getName() + "\t" + Thread.interrupted());
        System.out.println("----1----");
        Thread.currentThread().interrupt(); // 中断标识位设置为true
        System.out.println("----2----");
        System.out.println(Thread.currentThread().getName() + "\t" + Thread.interrupted());
        System.out.println(Thread.currentThread().getName() + "\t" + Thread.interrupted());
    }

}

输出结果:
main	false
main	false
----1----
----2----
main	true
main	false
都会返回中断状态,两者对比

对于静态方法Thread.interrupted()和实例方法Thread.currentThread().isInterrupted()区别在于:

  • 静态方法interrupted将会清除中断状态(传入的参数ClearInterrupted为true)
  • 实例方法isInterrupted则不会(传入的参数ClearInterrupted为false)

在这里插入图片描述

总结

线程中断相关方法:

public void interrupt() 是一个实例方法,它通知目标线程中断,也仅仅是设置目标线程的中断标志位为true

public boolean isInterrupted() 是一个实例方法,它判断当前线程是否被中断(通过检查中断标志位)并获取中断标志

public static boolean interrupted() 是一个静态方法,返回当前线程的中断真实状态(boolean类型)后会将当前线程的中断状态设为false,此方法调用之后会清楚当前线程的中断标志位的状态(将中断标志置为false了),返回当前值并清零置为false

LockSupport是什么

概念

java.util.concurrent.locks.LockSupport类是用来创建锁和其他同步类的基本线程阻塞原语,其中park()和unpack()而作用分别是阻塞线程和解除被阻塞线程

方法摘要

在这里插入图片描述

线程等待唤醒机制

三种让线程等待和唤醒的方法

  1. 使用Object中的wait()方法让线程等待,使用Object中的notify()方法唤醒线程
  2. 使用JUC包中的Condition的await()方法让线程等待,使用signal()方法唤醒线程
  3. LockSupport类可以阻塞当前线程以及唤醒指定被阻塞的线程

Object类中的wait和notify方法实现线程等待和唤醒

Code
正常
package com.imooc.springcloud.locksupport;

import java.util.concurrent.TimeUnit;

public class WaitNotifyDemo {

    public static void main(String[] args) {
        Object objectLock = new Object();
        new Thread(() -> {
            synchronized (objectLock) {
                System.out.println(Thread.currentThread().getName() + "\t --------come in");
                try {
                    objectLock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "\t --------被唤醒");
            }
        }, "t1").start();

        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(() -> {
            synchronized (objectLock) {
                objectLock.notify();
                System.out.println(Thread.currentThread().getName() + "\t --------发出通知");
            }
        }, "t2").start();
    }

}

输出结果:
t1	 --------come in
t2	 --------发出通知
t1	 --------被唤醒
异常1
package com.imooc.springcloud.locksupport;

import java.util.concurrent.TimeUnit;

public class WaitNotifyDemo2 {

    public static void main(String[] args) {
        Object objectLock = new Object();
        new Thread(() -> {
//            synchronized (objectLock) {
                System.out.println(Thread.currentThread().getName() + "\t --------come in");
                try {
                    objectLock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "\t --------被唤醒");
//            }
        }, "t1").start();

        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(() -> {
//            synchronized (objectLock) {
                objectLock.notify();
                System.out.println(Thread.currentThread().getName() + "\t --------发出通知");
//            }
        }, "t2").start();
    }

}

输出结果:
t1	 --------come in
Exception in thread "t1" java.lang.IllegalMonitorStateException
	at java.lang.Object.wait(Native Method)
	at java.lang.Object.wait(Object.java:502)
	at com.imooc.springcloud.locksupport.WaitNotifyDemo2.lambda$main$0(WaitNotifyDemo2.java:13)
	at java.lang.Thread.run(Thread.java:750)
Exception in thread "t2" java.lang.IllegalMonitorStateException
	at java.lang.Object.notify(Native Method)
	at com.imooc.springcloud.locksupport.WaitNotifyDemo2.lambda$main$1(WaitNotifyDemo2.java:29)
	at java.lang.Thread.run(Thread.java:750) 
异常2
package com.imooc.springcloud.locksupport;

import java.util.concurrent.TimeUnit;

public class WaitNotifyDemo3 {

    public static void main(String[] args) {
        Object objectLock = new Object();
        new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (objectLock) {
                System.out.println(Thread.currentThread().getName() + "\t --------come in");
                try {
                    objectLock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "\t --------被唤醒");
            }
        }, "t1").start();


        new Thread(() -> {
            synchronized (objectLock) {
                objectLock.notify();
                System.out.println(Thread.currentThread().getName() + "\t --------发出通知");
            }
        }, "t2").start();
    }

}

输出结果:
t2	 --------发出通知
t1	 --------come in
... 	// 程序未结束    
小总结
  1. wait和notify方法必须要在同步代码块或者方法里面,且成对出现使用
  2. 先wait再notify才ok,否则程序无法执行,无法唤醒

Condition接口中的await和signal方法实现线程的等待和唤醒

Code
正常
package com.imooc.springcloud.locksupport;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class AwaitSignalDemo {

    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 --------come in");
                condition.await();
                System.out.println(Thread.currentThread().getName() + "\t --------被唤醒");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }, "t1").start();

        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(() -> {
            lock.lock();
            try {
                condition.signal();
                System.out.println(Thread.currentThread().getName() + "\t --------发出通知");
            } finally {
                lock.unlock();
            }
        }, "t2").start();
    }

}

输出结果:
t1	 --------come in
t2	 --------发出通知
t1	 --------被唤醒    
异常1
package com.imooc.springcloud.locksupport;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class AwaitSignalDemo2 {

    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 --------come in");
                condition.await();
                System.out.println(Thread.currentThread().getName() + "\t --------被唤醒");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
//                lock.unlock();
            }
        }, "t1").start();

        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(() -> {
//            lock.lock();
            try {
                condition.signal();
                System.out.println(Thread.currentThread().getName() + "\t --------发出通知");
            } finally {
//                lock.unlock();
            }
        }, "t2").start();
    }

}

输出结果:
t1	 --------come in
t1	 --------come in
Exception in thread "t1" 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.AbstractQueuedSynchronizer.fullyRelease(AbstractQueuedSynchronizer.java:1723)
	at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:2036)
	at com.imooc.springcloud.locksupport.AwaitSignalDemo2.lambda$main$0(AwaitSignalDemo2.java:18)
	at java.lang.Thread.run(Thread.java:750)
Exception in thread "t2" java.lang.IllegalMonitorStateException
	at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.signal(AbstractQueuedSynchronizer.java:1939)
	at com.imooc.springcloud.locksupport.AwaitSignalDemo2.lambda$main$1(AwaitSignalDemo2.java:36)
	at java.lang.Thread.run(Thread.java:750) 
异常2
package com.imooc.springcloud.locksupport;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class AwaitSignalDemo3 {

    public static void main(String[] args) {
        Lock lock = new ReentrantLock();
        Condition condition = lock.newCondition();

        new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            lock.lock();
            try {
                System.out.println(Thread.currentThread().getName() + "\t --------come in");
                condition.await();
                System.out.println(Thread.currentThread().getName() + "\t --------被唤醒");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }, "t1").start();

        new Thread(() -> {
            lock.lock();
            try {
                condition.signal();
                System.out.println(Thread.currentThread().getName() + "\t --------发出通知");
            } finally {
                lock.unlock();
            }
        }, "t2").start();
    }

}

输出结果:
t2	 --------发出通知
t1	 --------come in 
... 	// 程序未结束
小总结
  1. Condition中的线程等待和唤醒方法,需要先获取锁
  2. 一定要先await后signal,不要反了,否则程序无法执行,无法唤醒

上述两个对象Object和Condition使用的限制条件

  1. 线程需要先获得并持有锁,必须在锁块(synchronized或lock)中
  2. 必须要先等待后唤醒,线程才能够被唤醒

LockSupport类中的park等待和unpark唤醒

LockSupport是什么

LockSupport 是用于创建锁和其他同步类的基本线程阻塞原语

LockSupport类使用了一种名为Permit(许可)的概念来做到阻塞和唤醒线程的功能,每个线程都有一个许可(Permit)

但是与Semaphore不同,许可证只能有一个,累加上限是1

主要方法
// 阻塞当前线程
// peimit许可证默认没有不能放行,所以一开始调用park()方法当前线程会阻塞,直到别的线程给当前线程发放peimit,park方法才会被唤醒
public static void park() {
    UNSAFE.park(false, 0L);
}

// 阻塞传入的具体线程
public static void park(Object blocker) {
    Thread t = Thread.currentThread();
    setBlocker(t, blocker);
    UNSAFE.park(false, 0L);
    setBlocker(t, null);
}

public native void park(boolean var1, long var2);

// 唤醒处于阻塞状态的指定线程
// 调用unpack(thread)方法后 就会将thread线程的许可证peimit发放,会自动唤醒park线程,即之前阻塞中的LockSupport.park()方法会立即返回
public static void unpark(Thread thread) {
    if (thread != null)
        UNSAFE.unpark(thread);
}

public native void unpark(Object var1);
Code1
package com.imooc.springcloud.locksupport;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;

public class ParkDemo {

    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + "\t --------come in");
            LockSupport.park();
            System.out.println(Thread.currentThread().getName() + "\t --------被唤醒");
        }, "t1");

        t1.start();

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(() -> {
            LockSupport.unpark(t1);
            System.out.println(Thread.currentThread().getName() + "\t --------发出通知");
        }, "t2").start();
    }

}

输出结果:
t1	 --------come in
t1	 --------被唤醒
t2	 --------发出通知    
Code2
package com.imooc.springcloud.locksupport;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;

public class ParkDemo2 {

    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "\t --------come in,当前时间:" + System.currentTimeMillis());
            LockSupport.park();
            System.out.println(Thread.currentThread().getName() + "\t --------被唤醒,当前时间:" + System.currentTimeMillis());
        }, "t1");

        t1.start();

        new Thread(() -> {
            LockSupport.unpark(t1);
            System.out.println(Thread.currentThread().getName() + "\t --------发出通知");
        }, "t2").start();
    }

}

输出结果:
t2	 --------发出通知
t1	 --------come in,当前时间:1699280068622
t1	 --------被唤醒,当前时间:1699280068622   
结论
  1. 满足正常无锁块的要求
  2. 之前错误的先唤醒后等待,LockSupport照样支持(t1线程sleep方法3秒后醒来,执行park无效,没有阻塞效果,因为先执行了unpark(t1)导致上面的park方法形同虚设,无效,所以输出时间一样【类似高速公路的ETC,提前买好了通行证unpark,到闸机处直接抬起栏杆放行了,没有park拦截了】)
  3. 成双成对出现要牢记
重点说明(重要)
异常Code
package com.imooc.springcloud.locksupport;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;

public class ParkDemo3 {

    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "\t --------come in,当前时间:" + System.currentTimeMillis());
            LockSupport.park();
            LockSupport.park();
            System.out.println(Thread.currentThread().getName() + "\t --------被唤醒,当前时间:" + System.currentTimeMillis());
        }, "t1");

        t1.start();

        new Thread(() -> {
            LockSupport.unpark(t1);
            LockSupport.unpark(t1);
            LockSupport.unpark(t1);
            LockSupport.unpark(t1);
            System.out.println(Thread.currentThread().getName() + "\t --------发出通知");
        }, "t2").start();
    }

}

输出结果:
t2	 --------发出通知
t1	 --------come in,当前时间:1699280417620
...		// 程序未停止
总结

LockSupport是用来创建锁和其他同步类的基本线程阻塞原语

LockSupport是一个线程阻塞工具类,所有的方法都是静态方法,可以让线程在任意位置阻塞,阻塞后也有对应的唤醒方法。归根结底,LockSupport是调用Unsafe中的native代码

LockSupport提供park()和unpark()方法实现阻塞线程和解除线程阻塞的过程:LockSupport和每个使用它的线程都有一个许可(Peimit)关联,每个线程都有一个相关的permit,peimit最多只有一个,重复调用unpark也不会积累凭证

形象理解:线程阻塞需要消耗凭证(Permit),这个凭证最多只有一个

当调用park时

  • 如果有凭证,则会直接消耗掉这个凭证然后正常退出
  • 如果没有凭证,则必须阻塞等待凭证可用

当调用unpark时

  • 它会增加一个凭证,但凭证最多只能有1各,累加无效
面试题

提问1:为什么LockSupport可以突破wait/notify的原有调用顺序?

解答1:因为unpark获得了一个凭证,之后再调用park方法,就可以名正言顺的凭证消费,故不会阻塞,先发放了凭证后续可以畅通无阻

提问2:为什么唤醒两次后阻塞两次,但最终结果还会阻塞线程?

解答2:因为凭证的数量最多为1,连续调用两次unpark和调用一次unpark效果一样,只会增加一个凭证,而调用两次park却需要消费两个凭证,证不够,不能放行

  • 21
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值