ReentrantLock实现wait和notify

ReentrantLock 可以配合Condition来实现wait和notify的await()和signalAll()来实现线程的等待和唤醒。

示例代码:

public class TestClass {
    private final Lock lock = new ReentrantLock();
    private final Condition condition = lock.newCondition();
    private int count;

    public void add() {
        try {
            lock.lock();
            try {
                for (int i = 0; i < 5; i++) {
                    count ++;
                    System.out.println("Test ReentrantLock "+Thread.currentThread()+" running");
                    System.out.println("Test ReentrantLock  "+count);
                    if(count == 2){
                        condition.await();
                    }

                }

            } finally {
                lock.unlock();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}
public class MyClass {

    public static void main(String[] args) {
        final TestClass testClass = new TestClass();
        new Thread(new Runnable() {
            @Override
            public void run() {
                testClass.add();
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {

                testClass.add();
            }
        }).start();
    }
    
}

运行结果:

 可以看到,Thread-0在输出2后停止了运行并由Thread-1继续运行下去


版权声明:本文为qq_40698103原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。