博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

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

Posted on 2013-07-28 18:27  钟悍  阅读(475)  评论(0编辑  收藏  举报
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