美文网首页
Condition处理消费者和生产者同步问题

Condition处理消费者和生产者同步问题

作者: small瓜瓜 | 来源:发表于2019-07-10 19:04 被阅读0次
使用ReentrantLockCondition处理消费者和生产者同步问题
public class Test {
    private static volatile int count;

    public static void main(String[] args) {
        Lock lock = new ReentrantLock();
        Condition empty = lock.newCondition();
        Condition fully = lock.newCondition();

        new Thread(() -> {
            while(true){
                lock.lock();
                System.out.println("--我是消费者:count = " + count);
                try {
                    while (count <= 0) {
                        empty.await();
                    }
                    count--;
                    if (count < 10) {
                        fully.signal();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }
        }).start();

        new Thread(() -> {
            while(true){
                lock.lock();
                System.out.println("我是生产者:count = " + count);
                try {
                    while (count >= 50) {
                        fully.await();
                    }
                    count++;
                    empty.signal();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }
        }).start();
    }
}

ReentrantLock默认是用非公平锁的方式,这样虽然会造成饥饿现象,但是吞吐量更大。

相关文章

网友评论

      本文标题:Condition处理消费者和生产者同步问题

      本文链接:https://www.haomeiwen.com/subject/jjjkkctx.html