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();
}
}
}
public static void main(String[] args){
Bus bus = new Bus();

ExecutorService threadPool = Executors.newCachedThreadPool();
threadPool.execute(new MyRunnable(1, bus));
threadPool.execute(new MyRunnable(2, bus));
threadPool.execute(new MyRunnable(3, bus));
threadPool.shutdown();
}

static class MyRunnable implements Runnable{
private int idx;
private Bus bus;

public MyRunnable(int idx, Bus bus) {
this.idx = idx;
this.bus = bus;
}

@Override
public void run() {
for(int i = 0; i < 10; i++) {
switch (idx) {
case 1: bus.doOne(); break;
case 2: bus.doTwo(); break;
case 3: bus.doThree(); break;
}
}
}
}

static class Bus{
private Lock lock = new ReentrantLock();
private Condition oneCondition = lock.newCondition();
private Condition twoCondition = lock.newCondition();
private Condition threeCondition = lock.newCondition();

private int should = 1;

public void doOne(){
lock.lock();

try{
while (should != 1) toWait(oneCondition);

System.out.println("do one");
should = 2;
twoCondition.signal();
}finally {
lock.unlock();
}
}

public void doTwo(){
lock.lock();

try{
while (should != 2) toWait(twoCondition);

System.out.println("do two");
should = 3;
threeCondition.signal();
}finally {
lock.unlock();
}
}

public void doThree(){
lock.lock();

try{
while (should != 3) toWait(threeCondition);

System.out.println("do three");
System.out.println("");
should = 1;
oneCondition.signal();
}finally {
lock.unlock();
}
}

private void toWait(Condition condition){
try {
condition.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
打赏