Thread communication java.util.concurrent.locks.Condition 用法(一)

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

public class ConditionTest {

    public static void main(String[] args) {
        final Bussiness bussiness = new Bussiness();
        final int times = 5;
        Thread a = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < times; i++) {
                    bussiness.forThreadA();
                }
            }
        });
        a.setName("ThreadA");

        Thread b = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < times; i++) {
                    bussiness.forThreadB();
                }
            }
        });
        b.setName("ThreadB");
        a.start();
        b.start();

    }

    static class Bussiness {
        private boolean shouldSubRun = true;
        private Lock lock = new ReentrantLock();
        Condition condition = lock.newCondition();

        public void forThreadA() {
            lock.lock();
            if (!shouldSubRun) {
                try {
                    condition.await();
                } catch (InterruptedException e) {
                }
            }
            for (int i = 1; i <= 3; i++) {
                System.out.println(Thread.currentThread().getName() + " " + i);
            }
            shouldSubRun = false;
            condition.signal();
            lock.unlock();
        }

        public void forThreadB() {
            lock.lock();
            while (shouldSubRun) {
                try {
                    condition.await();
                } catch (InterruptedException e) {
                }
            }
            for (int i = 1; i <= 2; i++) {
                System.out.println(Thread.currentThread().getName() + " " + i);
            }
            shouldSubRun = true;
            condition.signal();
            lock.unlock();
        }
    }

}

output:

ThreadA 1
ThreadA 2
ThreadA 3
ThreadB 1
ThreadB 2
ThreadA 1
ThreadA 2
ThreadA 3
ThreadB 1
ThreadB 2
ThreadA 1
ThreadA 2
ThreadA 3
ThreadB 1
ThreadB 2
ThreadA 1
ThreadA 2
ThreadA 3
ThreadB 1
ThreadB 2
ThreadA 1
ThreadA 2
ThreadA 3
ThreadB 1
ThreadB 2

原文地址:https://www.cnblogs.com/zhonghan/p/3221375.html