首页 > 代码库 > java利用lock和unlock实现消费者与生产者问题(多线程)

java利用lock和unlock实现消费者与生产者问题(多线程)

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LockAndUnlockDemo {

    public static void main(String[] args) {
        Clerk2 c=new Clerk2();
        Thread t=new Thread(new Producer2(c));
        Thread t1=new Thread(new Consumer2(c));
        t.start();
        t1.start();
    }

}
class Clerk2{
    private int product=0;//生产者生产的数量给店员
    private Lock lock = new ReentrantLock();
    private Condition condition_pro = lock.newCondition();
    private Condition condition_con = lock.newCondition();
    
    public void addproduct(){
        lock.lock();
        try {
            if(this.product>5){
                try {
                    condition_con.await();
                } catch (InterruptedException e) {
                    
                    e.printStackTrace();
                }
            }else{
                product++;
                System.out.println("生产了第"+product+"个商品");
                condition_con.signal();
            }
        }finally {
            lock.unlock();
        }
    }
    public void getproduct(){
        lock.lock();
        try {
            if(this.product<=0){
                try {
                    condition_con.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            else{
                System.out.println("消费者买走了第"+product+"个商品");
                product--;
                condition_pro.signal();
            }
        } finally {
            lock.unlock();
        }
        
    }
}
class Producer2 implements Runnable{
    private Clerk2 clerk;
    
    public Producer2(Clerk2 clerk) {
        super();
        this.clerk = clerk;
    }

    public void run() {
        System.out.println("开始生产商品");
        while(true){
            try {
                Thread.sleep((int)(Math.random()*10)*1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            clerk.addproduct();
        }
        
    }
    
}
class Consumer2 implements Runnable{
    private Clerk2 clerk;
    
    public Consumer2(Clerk2 clerk) {
        super();
        this.clerk = clerk;
    }

    public void run() {
        System.out.println("消费者买走商品");
        while(true){
            try {
                Thread.sleep((int)(Math.random()*10)*1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            clerk.getproduct();
        }
        
    }
    
}


本文出自 “橙子的成长记录” 博客,请务必保留此出处http://azhome.blog.51cto.com/9306775/1547231

java利用lock和unlock实现消费者与生产者问题(多线程)