本帖最后由 ender 于 2014-6-8 23:28 编辑
经典的生产者和消费者模型 用的Lock接口加的锁
- class StorageLock {
- int count;
- String product;
- boolean flag;
- Lock lock = new ReentrantLock();
- Condition con = lock.newCondition();
- Condition pro = lock.newCondition();
-
- public void produce(String product){
- lock.lock();
- try{
- while(flag)
- pro.await();
- this.product=product;
- count++;
- System.out.println(product+"...Producer..."+count);
- flag=true;
- con.signal();
- }
- catch(InterruptedException e){}
- finally{
- lock.unlock();
- }
- }
- public void consume(){
- lock.lock();
- try{
- while(!flag)
- con.await();
- System.out.println(product+"...Consumer......."+count);
- flag=false;
- pro.signal();
- }
- catch(InterruptedException e){}
- finally{
- lock.unlock();
- }
- }
- }
- class ProducerLock implements Runnable{
- StorageLock sto;
- ProducerLock(StorageLock sto){
- this.sto=sto;
- }
- public void run(){
- while(true)
- sto.produce("commodity");
- }
- }
- class ConsumerLock implements Runnable{
- StorageLock sto;
- ConsumerLock(StorageLock sto){
- this.sto=sto;
- }
- public void run(){
- while(true)
- sto.consume();
- }
- }
- class ProducerConsumerLock{
- public static void main(String[] args){
- StorageLock sto = new StorageLock();
- new Thread(new ProducerLock(sto)).start();
- new Thread(new ProducerLock(sto)).start();
- new Thread(new ConsumerLock(sto)).start();
- new Thread(new ConsumerLock(sto)).start();
- }
- }
复制代码
|