一个经典的多线程condition使用实例代码,请评论

2021/5/2 18:27:37

本文主要是介绍一个经典的多线程condition使用实例代码,请评论,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

class BoundedBuffer {
final Lock lock = new ReentrantLock();
final Condition notFull = lock.newCondition();
final Condition notEmpty = lock.newCondition();

final Object[] items = new Object[100];
int putptr, takeptr, count;

public void put(Object x) throws InterruptedException {
lock.lock();
try {
while (count == items.length)
notFull.await();
items[putptr] = x;
if (++putptr == items.length) putptr = 0;
++count;
notEmpty.signal();
} finally {
lock.unlock();
}
}

public Object take() throws InterruptedException {
lock.lock();
try {
while (count == 0)
notEmpty.await();
Object x = items[takeptr];
if (++takeptr == items.length) takeptr = 0;
–count;
notFull.signal();
return x;
} finally {
lock.unlock();
}
}
}



这篇关于一个经典的多线程condition使用实例代码,请评论的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程