生产者消费者的多种方式实现

前言:生产者消费者模式是工作中多线程开发很常用的一种模式,也是笔试面试高频考点

1.使用阻塞队列实现

(阻塞队列有很多,如ArrayBlockingQueue,LinkedBlockingQueue,PriorityBlockingQueue,SynchronousQueue)


/**
 * 使用阻塞队列实现
 *
 * @author m969130721@163.com
 * @date 18-10-14 上午11:10
 */
public class BlockingQueueDemo {


    public static void main(String[] args) {

        BlockingQueue blockingQueue = new LinkedBlockingQueue(1);
        ProductFactory productFactory = new ProductFactory(blockingQueue);
        Customer customer = new Customer(blockingQueue);
        Thread productFactoryThread = new Thread(productFactory);
        Thread customerThread1 = new Thread(customer);
        Thread customerThread2 = new Thread(customer);

        productFactoryThread.start();
        customerThread1.start();
        customerThread2.start();

    }

}

/**
 * 生产者
 */
class ProductFactory implements Runnable {

    private BlockingQueue<Product> blockingQueue;

    ProductFactory(BlockingQueue<Product> blockingQueue) {
        this.blockingQueue = blockingQueue;
    }


    @Override
    public void run() {
            while (true) {
                Product product = new Product("产品");
                try {
//                    System.out.println(Thread.currentThread().getName() + " 生产者生产准备开始.............");
                    blockingQueue.put(product);
                    System.out.println(Thread.currentThread().getName() + " 添加一个产品:" + product);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
    }
}

/**
 * 消费者
 */
class Customer implements Runnable {
    private BlockingQueue<Product> blockingQueue;

    Customer(BlockingQueue<Product> blockingQueue) {
        this.blockingQueue = blockingQueue;
    }

    @Override
    public void run() {
            try {
//                System.out.println(Thread.currentThread().getName() + " 消费者消费准备开始..............");
                Product product = blockingQueue.take();
                System.out.println(Thread.currentThread().getName() + " 取出一个产品:"+product);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
    }
}


class Product {
    private String name;

    Product(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Product{" +
                "name='" + name + '\'' +
                '}';
    }
}

 

2.使用显示锁Lock实现:

/**
 * 两个Condition实现
 *
 * @author m969130721@163.com
 * @date 18-10-14 下午3:11
 */
public class LockDemo {


    public static void main(String[] args) {
        Gift gift = new Gift("礼物", 998, false);
        ReentrantLock reentrantLock = new ReentrantLock();

        //读写分离锁,生产一个,消费者一个
        Condition productCondition = reentrantLock.newCondition();
        Condition customerCondition = reentrantLock.newCondition();


        GiftFactory factory = new GiftFactory(gift, reentrantLock, productCondition, customerCondition);
        SendGift sendGift = new SendGift(gift, reentrantLock, productCondition, customerCondition);


        Thread giftFactory = new Thread(factory);
        Thread sendGift1 = new Thread(sendGift);
        Thread sendGift2 = new Thread(sendGift);
        giftFactory.start();
        sendGift1.start();
        sendGift2.start();

    }


}

class Gift {
    private String name;
    private float price;
    private boolean flag;

    Gift(String name, float price, boolean flag) {
        this.name = name;
        this.price = price;
        this.flag = flag;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public float getPrice() {
        return price;
    }

    public void setPrice(float price) {
        this.price = price;
    }

    public boolean isFlag() {
        return flag;
    }

    public void setFlag(boolean flag) {
        this.flag = flag;
    }

    @Override
    public String toString() {
        return "Gift{" +
                "name='" + name + '\'' +
                ", price=" + price +
                ", flag=" + flag +
                '}';
    }
}


/**
 * 消费者
 */
class GiftFactory implements Runnable {
    private Gift gift;
    private ReentrantLock reentrantLock;
    private Condition productCondition;
    private Condition customerCondition;

    GiftFactory(Gift gift, ReentrantLock reentrantLock, Condition productCondition, Condition customerCondition) {
        this.gift = gift;
        this.reentrantLock = reentrantLock;
        this.productCondition = productCondition;
        this.customerCondition = customerCondition;
    }

    @Override
    public void run() {
        while (true) {
            try {
                reentrantLock.lock();
                //有礼物
                if (gift.isFlag()) {
                    productCondition.await();
                }
                System.out.println("生产gift:" + gift.getName() + ",price:" + gift.getPrice());
                gift.setFlag(true);
                customerCondition.signal();

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                reentrantLock.unlock();
            }
        }
    }

}

class SendGift implements Runnable {

    private Gift gift;

    private ReentrantLock reentrantLock;

    private Condition productCondition;

    private Condition customerCondition;

    SendGift(Gift gift, ReentrantLock reentrantLock, Condition productCondition, Condition customerCondition) {
        this.reentrantLock = reentrantLock;
        this.gift = gift;
        this.productCondition = productCondition;
        this.customerCondition = customerCondition;
    }

    @Override
    public void run() {
        try {
            reentrantLock.lock();
            //没有礼物
            if (!gift.isFlag()) {
                customerCondition.await();
            }
            System.out.println("发送gift:" + gift.getName() + ",price:" + gift.getPrice());
            gift.setFlag(false);
            productCondition.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            reentrantLock.unlock();
        }
    }
}

 

3.隐式锁实现:

/**
 * @author m969130721@163.com
 * @date 18-10-14 下午1:59
 */
public class SynchronizedDemo {

    public static void main(String[] args) {
        Food food = new Food("offer",12*14,false);
        FoodFactory foodFactory = new FoodFactory(food);
        EatFood eatFood = new EatFood(food);
        Thread createThread = new Thread(foodFactory);
        Thread eatThread1 = new Thread(eatFood);
        Thread eatThread2 = new Thread(eatFood);

        createThread.start();
        eatThread1.start();
        eatThread2.start();
    }
}

class Food {
    private String name;
    private float price;
    private boolean flag;

    Food(String name,float price,boolean flag){
        this.name = name;
        this.price = price;
        this.flag = flag;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public float getPrice() {
        return price;
    }

    public void setPrice(float price) {
        this.price = price;
    }

    public boolean isFlag() {
        return flag;
    }

    public void setFlag(boolean flag) {
        this.flag = flag;
    }

    @Override
    public String toString() {
        return "Food{" +
                "name='" + name + '\'' +
                ", price=" + price +
                ", flag=" + flag +
                '}';
    }
}

/**
 * 生产者
 */
class FoodFactory implements Runnable {
    private Food food;

    FoodFactory(Food food) {
        this.food = food;
    }

    @Override
    public void run() {
        while (true) {
            synchronized (food) {
                //存在
                if (food.isFlag()) {
                    try {
                        food.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                food.setFlag(true);
                System.out.println("生产商品:" + food.getName() + ",价格:" + food.getPrice());
                food.notify();
            }
        }
    }
}

/**
 * 消费者
 */
class EatFood implements Runnable {
    private Food food;

    EatFood(Food food) {
        this.food = food;
    }

    @Override
    public void run() {
        synchronized (food) {
            //不存在
            if (!food.isFlag()) {
                try {
                    food.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            food.setFlag(false);
            System.out.println("消费商品:" + food.getName() + ",价格:" + food.getPrice());
            food.notify();
        }
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值