Java并发工具类LockSupport

LockSupport

J.U.C框架中有一个叫做LockSupport的类,可以精准地阻塞和唤醒特定的线程,并作为其他同步类的原语。
LockSupport包含一个park(Object blocker)和unpark(Object blocker)方法,分别用于阻塞和唤醒。

举个例子,下面的代码包含一个线程thread1和主线程,在thread1中调用park方法,在主线程中调用unpark,然后打印thread1的状态:

import java.util.concurrent.locks.LockSupport;


public class Main{
    public static void main(String[] args) throws InterruptedException {

    Thread thread1 = new Thread(new Runnable() {

        @Override
        public void run() {
        System.out.println("thread 1 start");
        LockSupport.park(Thread.currentThread());
        try {
            Thread.sleep(4000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("thread 1 end");
        }
    });
    thread1.start();
    System.out.println("main thread start,thread1 "+thread1.getState());
    Thread.sleep(2000);
    System.out.println("main thread running,thread1 "+thread1.getState());
    LockSupport.unpark(thread1);
    Thread.sleep(6000);
    System.out.println("main thread end,thread1 "+thread1.getState());
    }
}

执行结果:

thread 1 start
main thread start,thread1 RUNNABLE
main thread running,thread1 WAITING
thread 1 end
main thread end,thread1 TERMINATED

可以看到,park之后thread1变成WAITTING,unpark之后唤醒继续执行直到结束

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值