import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class LockTest10050 {
public static void main(String[] args) {
final Bussiness bussiness = new Bussiness();
new Thread(new Runnable() {
public void run() {
for (int i = 1; i < 51; i++) {
bussiness.sub(i);
}
}
}).start();
new Thread(new Runnable() {
public void run() {
for (int i = 1; i < 51; i++) {
bussiness.main(i);
}
}
}).start();
}
}
class Bussiness {
Lock lock = new ReentrantLock();
Condition condition = lock.newCondition();
boolean flag = true;
public void sub(int i) {
lock.lock();
try {
while (!flag)
condition.await();
for (int j = 1; j < 11; j++) {
System.out.println("子线程第" + i + "次循环: 次数为" + j);
}
flag = false;
condition.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void main(int i) {
lock.lock();
try {
while (flag)
condition.await();
for (int j = 1; j < 101; j++) {
System.out.println("主线程第" + i + "次循环: 次数为" + j);
}
flag = true;
condition.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
API文档中实例代码:
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(); } } }