java的Lock使用

package com.wcfb.service;

import cn.hutool.core.thread.ThreadUtil;

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

/**
 * @author wcfb
 * @time 2021/3/15/015.
 * @since
 */
public class LockTestService {

    static Lock lock = new ReentrantLock();
    static Condition condition = lock.newCondition();

    public static void main(String[] args) {
        LockTestService lockTestService = new LockTestService();
        Thread awaitThread = new Thread(() -> {
            lockTestService.await();
        });
        Thread signAllThread = new Thread(() -> {
            lockTestService.signAll();
        });
        try {
            awaitThread.start();
            ThreadUtil.sleep(1000);
            signAllThread.start();
        } catch (Exception e){
            e.printStackTrace();
        }
    }

    public void await() {
        try {
            lock.lock();
            System.out.println(Thread.currentThread().getName() + "准备进行等待");
            condition.await();
            System.out.println(Thread.currentThread().getName() + "结束等待");
            lock.unlock();
        } catch (Exception e) {

        }
    }

    public void signAll() {
        lock.lock();
        System.out.println(Thread.currentThread().getName() + "准备通知");
        condition.signal();
        System.out.println(Thread.currentThread().getName() + "通知完后在再释放锁");
        System.out.println(Thread.currentThread().getName() + "通知结束");
        lock.unlock();
    }

}
image.png

你可能感兴趣的:(java的Lock使用)