更新时间:2022-06-01 09:38:24
// 暂停当前线程 LockSupport.park(); // 恢复某个线程的运行 LockSupport.unpark(暂停线程对象)
与 Object 的 wait & notify 相比
先Park后Unpark
package com.gzczy.concurrent.week3; import lombok.extern.slf4j.Slf4j; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.LockSupport; /** * @Description Park和Unpark * @Author chenzhengyu * @Date 2020-11-05 19:15 */ topic = "c.ParkAndUnParkDemo") (public class ParkAndUnParkDemo { public static void main(String[] args) { // demo1(); demo2(); } public static void demo1(){ Thread t1 = new Thread(() -> { log.debug("start..."); try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } log.debug("park..."); LockSupport.park(); log.debug("resume..."); },"t1"); t1.start(); try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); } log.debug("unpark..."); LockSupport.unpark(t1); } //先Unpark再Park public static void demo2(){ Thread t1 = new Thread(() -> { log.debug("start..."); try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); } log.debug("park..."); LockSupport.park(); log.debug("resume..."); }, "t1"); t1.start(); try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } log.debug("unpark..."); LockSupport.unpark(t1); } }
为线程调度目的禁用当前线程,除非许可可用。
如果许可证是可用的,那么它将被消耗,调用将立即返回。否则,当前线程会因为线程调度的目的而被暂停,并处于休眠状态,直到以下三种情况之一发生:
park方法不会告知你是哪一种情况的发生而导致的。调用者应该重新检查导致线程停在第一个位置的条件。调用者也可以确定,例如,线程返回时的中断状态。
/** * Disables the current thread for thread scheduling purposes unless the * permit is available. * * <p>If the permit is available then it is consumed and the call returns * immediately; otherwise * the current thread becomes disabled for thread scheduling * purposes and lies dormant until one of three things happens: * * <ul> * <li>Some other thread invokes {@link #unpark unpark} with the * current thread as the target; or * * <li>Some other thread {@linkplain Thread#interrupt interrupts} * the current thread; or * * <li>The call spuriously (that is, for no reason) returns. * </ul> * * <p>This method does <em>not</em> report which of these caused the * method to return. Callers should re-check the conditions which caused * the thread to park in the first place. Callers may also determine, * for example, the interrupt status of the thread upon return. * * @param blocker the synchronization object responsible for this * thread parking * @since 1.6 */ public static void park(Object blocker) { Thread t = Thread.currentThread(); setBlocker(t, blocker); UNSAFE.park(false, 0L); setBlocker(t, null); }
unpark通过传入当前线程进行取消park
/** * Makes available the permit for the given thread, if it * was not already available. If the thread was blocked on * {@code park} then it will unblock. Otherwise, its next call * to {@code park} is guaranteed not to block. This operation * is not guaranteed to have any effect at all if the given * thread has not been started. * * @param thread the thread to unpark, or {@code null}, in which case * this operation has no effect */ public static void unpark(Thread thread) { if (thread != null) UNSAFE.unpark(thread); }
LockSupport的主要作用就是让线程进入阻塞等待和唤醒状态
我们常见的三种线程唤醒的方法
Object类中的wait和notify方法实现线程等待和唤醒
package com.gzczy.concurrent.heima.b.wait; import lombok.extern.slf4j.Slf4j; import java.util.concurrent.TimeUnit; /** * @Description wait notify 测试阻塞 * @Author chenzhengyu * @Date 2021年01月31日 14:12:08 */ topic = "c.WaitNotifyDemo") (public class WaitNotifyDemo2 { final static Object obj = new Object(); public static void main(String[] args) throws Exception { new Thread(() -> { try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (obj) { log.debug("执行...."); try { obj.wait(); // 让线程在obj上一直等待下去 } catch (InterruptedException e) { e.printStackTrace(); } log.debug("其它代码...."); } },"t1").start(); new Thread(() -> { synchronized (obj) { log.debug("执行...."); obj.notify(); // 让线程在obj上一直等待下去 log.debug("其它代码...."); } },"t2").start(); } }
异常1:wait方法和notify方法,两个都去掉同步代码块,抛出IllegalMonitorStateException
异常2:将notify放在wait方法前面,程序将无法执行,无法进行唤醒
总结:wait和notify方法必须要在同步代码块中或者方法里面成对进行出现才能使用,而且必须先wait后notify之后才OK
通过Park和Unpark进行实现线程等待和唤醒
package com.gzczy.concurrent.heima.b.wait; import lombok.extern.slf4j.Slf4j; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.LockSupport; /** * @Description LockSupport Demo 进行线程阻塞 * @Author chenzhengyu * @Date 2021-01-31 14:22 */ topic = "c.LockSupportDemo") (public class LockSupportDemo { public static void main(String[] args) throws InterruptedException { //默认是permit 0 Thread t1 = new Thread(() -> { try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); } log.debug("执行....是否打断--->"+Thread.currentThread().isInterrupted()); // 调用一次park就会消费permit 由刚刚的1变为0 你继续运行下去吧 LockSupport.park(); log.debug("其它代码,是否打断--->"+Thread.currentThread().isInterrupted()); //再次打住 目前没有许可了 许可为0 那就不放你继续运行啦 LockSupport.park(); log.debug("再次park,是否打断--->"+Thread.currentThread().isInterrupted()); //被打断后会发现无法park住,打断标记已经为true 线程已经被打断了 LockSupport.park(); }, "t1"); t1.start(); new Thread(() -> { log.debug("执行...."); //调用一次unpark就加1变成1,线程还在运行 没毛病老铁 你继续运行吧 LockSupport.unpark(t1); log.debug("其它代码...."); }, "t2").start(); try { TimeUnit.SECONDS.sleep(4); log.debug("打断t1线程...."); t1.interrupt(); } catch (InterruptedException e) { e.printStackTrace(); } } }
运行结果
优势对比
每个线程都有自己的一个 Parker 对象(底层C代码实现),由三部分组成 _counter , _cond 和 _mutex 打个比喻
1. 调用 Unsafe.unpark(Thread_0) 方法,设置 _counter 为 1
2. 当前线程调用 Unsafe.park() 方法
3. 检查 _counter ,本情况为 1,这时线程无需阻塞,继续运行
4. 设置 _counter 为 0
LockSupport是用来创建锁和其他同步类的基本线程阻塞原语,它使用了一种名为Permit(许可)的概念来做到阻塞和唤醒线程的功能,每个线程都有一个许可(Permit),Permit只有两个值:1和0,默认是0。我们可以把许可看成是一种信号量(Semaphore),但是与Semaphore不同的是,许可的累加上限是1
LockSupport是一个线程阻塞工具,所有的方法都是静态方法,可以让线程在任意位置进行阻塞。阻塞之后也有对应的唤醒方法,归根结底,LockSupport调用的是UnSafe里面的native代码
LockSupport提供了Park和Unpark的方法实现阻塞线程和解除线程阻塞的过程
LockSupport和每个使用它的线程都有一个许可(Permit)进行关联,Permit相当于1,0的开关,默认是0
调用一次unpark就加1变成1,调用一次park就会消费permit,也就是将1变成0的这个过程,同时将park立即返回
如果再次调用park会变成阻塞(因为Permit为0,所以会阻塞在这里,直至Permit变为1),如果这个时候调用unpark会把permit设置为1。每个线程都有一个相关的Permit,Permit最多只有1个,重复调用unpark也不会积累凭证
为什么可以先唤醒线程后阻塞线程?
答:因为UnPark获得了一个凭证,之后调用Park方法,就可以名正言顺的凭证消费,故不会阻塞
为什么唤醒两次后阻塞两次,但是最终的结果还是会阻塞线程?
答:因为凭证的数量最多为1,连续调用两次unpark和调用一次unpark的效果是一样的,只会增加一个凭证;而调用两次park却需要消费两个凭证,证不够,不能放行