JAVA JUC 用同步锁解决生产者消费者问题

JAVA多线程的形式比较独特,用的还是少了...

class Clerk{
    private int product;
    private ReentrantLock lock = new ReentrantLock();
    private Condition con = lock.newCondition();

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

        try {
            if(product<20){
                product++;
                System.out.println(Thread.currentThread().getName()+"生产一件商品");
                con.signalAll();
            }else{
                System.out.println("仓库已满");
                try {
                    con.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }
    public void sale(){
        lock.lock();
        try {
            if(product>0){
                System.out.println(Thread.currentThread().getName()+"消费一件商品");
                product--;
                con.signalAll();
            }else{
                System.out.println(Thread.currentThread().getName()+"没有商品");
                try {
                    con.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        } finally {
            lock.unlock();
        }
    }
}
class prductor implements Runnable{
    private Clerk c ;
    prductor(Clerk c){
        this.c=c;
    }
    @Override
    public void run() {
        while (true){
            c.get();
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }
}
class cus implements Runnable{
    private Clerk c ;
    cus(Clerk c){
        this.c=c;
    }
    @Override
    public void run() {
        while (true){
            c.sale();
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }
}
public class ProCusProblem{
    public static void main(String[] args) {
        Clerk c = new Clerk();
        prductor p = new prductor(c);
        cus cs = new cus(c);
        new Thread(p,"生产者1").start();
        new Thread(p,"生产者2").start();
        new Thread(p,"生产者3").start();
        new Thread(cs,"消费者1").start();

    }


}

 

posted @ 2020-03-12 14:26  超级学渣渣  阅读(156)  评论(0编辑  收藏  举报