今天被问了个这个问题,脑子当时给抽筋了,完全给木掉了,回来好好写了边,怎么会当时写不出来呢。。。
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Test421 extends Thread {
public void run() {
Customer a = new Customer();
a.start();
Producer b = new Producer();
b.start();
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Test421 c = new Test421();
c.start();
}
int key = 0;
Lock lock = new ReentrantLock();
Condition condempty = lock.newCondition();
Condition condfull = lock.newCondition();
class Customer extends Thread {
public void run() {
while (true) {
lock.lock();
try {
while (key < 1) {
// System.out.println("await");
condempty.await();
// System.out.println("start");
}
System.out.println("消费了" + key);
key--;
condfull.signalAll();
lock.unlock();
// return ;
Thread.sleep(12);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
class Producer extends Thread {
public void run() {
while (true) {
try {
// Thread.sleep(50);
lock.lock();
while (key >= 1000) {
condfull.await();
}
// a++;
key++;
System.out.println("生产了" + key);
// Thread.sleep(5000);
condempty.signalAll();
lock.unlock();
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
锁和条件这种方式比较重要的一点要注意的是:就算condition.sigalAll();别的线程也一定要等到lock的释放才可以继续下去,换句话说,await的时候很重要的一点是他会阻塞掉,并且隐含的会释放掉锁,这很关键,只有这样别的线程才能获得锁,才能继续执行下去。
而 sigalAll 的时候并不执行释放锁操作,只有显示的调用lock.unlock后,锁才被释放。