场景:一个线程因为某个condition不满足被挂起,直到该Condition被满足了,作用类似Object的wait/notify。
使用Condition完成似消费者生产者模型
package com.hts;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class ConditionTest {
final Lock lock = new ReentrantLock();
final Condition notFull = lock.newCondition();
final Condition notEmpty = lock.newCondition();
int maxSize;
List<Object> dataList=Collections.synchronizedList(new ArrayList<>());
public ConditionTest(int maxSize){
this.maxSize = maxSize;
}
public void put(String product) throws InterruptedException {
lock.lock();
try {
while (maxSize == dataList.size())
notFull.await();
dataList.add(new Object());
System.out.println(product+"生产一个产品,当前大小:"+dataList.size());
notEmpty.signal();
} finally {
lock.unlock();
}
}
public void take(String consumer) throws InterruptedException {
lock.lock();
try {
while (dataList.size() == 0)
notEmpty.await();
dataList.remove(0);
System.out.println(consumer+"消费一个产品当前大小:"+dataList.size());
notFull.signal();
} finally {
lock.unlock();
}
}
public static void main(String[] args) {
ConditionTest conditionTest = new ConditionTest(100);
for(int i = 0;i<1000;i++){
int id = i+1;
new Thread(new Runnable() {
@Override
public void run() {
try {
conditionTest.put("生产者"+id);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
try {
conditionTest.take("消费者"+id);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
}
}