LockSupport的 简单理解

在学习 SynchronousQueue 时,看到了 LockSupport 这个工具类;
因此写了一个demo 去理解下 unpark 与 park 的所谓的 permit

package threads.park;

import java.util.concurrent.locks.LockSupport;

/**
 * 用于理解 park 与 UnPark
 * upPark 相当于免停命令,持有一次 unPark 免于下一次 park() 的叫停,但再一次 park(),将会block
 */
public class ParkTest {
    public static void main(String[] args) throws InterruptedException {
        unParkOneButPark2();
//        unParkFirstParkThen();
    }

    static void unParkFirstParkThen() throws InterruptedException {
        Thread t = new Thread(() ->
        {
            LockSupport.unpark(Thread.currentThread());
            System.out.println("park itself first follow unPark");
            LockSupport.park();
            System.out.println("park itself second follow unPark");
            LockSupport.park();
            System.out.println("waked up by main thread");
        }

        );
        t.setName("thread -0 ");
        t.start();
        // main give up cpu ,let t1 run first
        t.join(5);
        // after t block itself ,main run
        LockSupport.unpark(t);
        System.out.println("main has tried to unPark " + t.getName());


        //park itself first follow unPark
        //park itself second follow unPark
        //waked up by main thread
        //main has tried to unPark thread -0 
    }

    static void unParkOneButPark2() throws InterruptedException {
        Thread t = new Thread(() ->
        {
            System.out.println(Thread.currentThread().getName() + " will be blocked myself");
            LockSupport.park();
            System.out.println(Thread.currentThread().getName() + " end first block");
            System.out.println(Thread.currentThread().getName() + " will call park again");
            LockSupport.park();
        }

        );
        t.setName("thread -1 ");
        t.start();
        // main give up cpu ,let t1 run
        t.join(5);
        LockSupport.unpark(t);
        System.out.println("main thread unPark " + t.getName());

        //thread -1  will be blocked
        //main thread unPark thread -1
        //thread -1  end first block
        //thread -1  will call park again
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值