使用ReentrantLock
的Condition
处理消费者和生产者同步问题
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
默认是用非公平锁的方式,这样虽然会造成饥饿现象,但是吞吐量更大。
网友评论