Java线程同步与阻塞ReentrantLock - Condition替换wait - notify

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

public class Main {
    private ReentrantLock lock = new ReentrantLock(false);
    private Condition condition = lock.newCondition();

    public static void main(String[] args) {
        Main main = new Main();
        main.test();
    }

    private void test() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                lock.lock();

                try {
                    Thread.sleep(3000);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                System.out.println("通知等待线程.");
                condition.signalAll();

                lock.unlock();
            }
        }).start();

        next();
    }

    private void next() {
        try {
            lock.lock();

            System.out.println("开始等待...");
            condition.await();

            lock.unlock();
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("等待结束.");
    }
}

 

输出:

开始等待...
通知等待线程
等待结束

 

你可能感兴趣的:(Java,线程,多线程,Java多线程,Java,多线程)