生产者消费者的java实现

先看最简单的,也就是缓冲区的容量为1

缓冲区容量为1

import java.util.List;

public class ProducerAndConsumer2 {
    static class AddThread implements Runnable {
        Plate plate;

        public AddThread(Plate p) {
            this.plate = p;
        }

        @Override
        public void run() {
            // TODO Auto-generated method stub
            plate.put(new Object());
        }
    }

    static class GetThread implements Runnable {
        Plate plate;

        public GetThread(Plate p) {
            this.plate = p;
        }

        @Override
        public void run() {
            // TODO Auto-generated method stub
            plate.get();
        }
    }

    static class Plate {
        private List<Object> egg = new ArrayList<Object>();

        public synchronized void put(Object o) {
            while (egg.size() > 0) {
                try {
                    System.out.println(
                            "此时盘子里有鸡蛋    生产线程"+Thread.currentThread().getName()+"阻塞");
                    this.wait();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            egg.add(0, o);
            System.out.println("生产线程放入一个鸡蛋");
            this.notifyAll();
        }
        
        public synchronized Object get() {
            while (egg.size() == 0) {
                try {
                    System.out.println(
                            "此时盘子里没有鸡蛋   消费线程"+Thread.currentThread().getName()+"阻塞");
                    this.wait();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

            Object object = egg.get(0);
            egg.clear();
            System.out.println("消费线程取得一个鸡蛋");
            this.notifyAll();
            return object;
        }
    }

    public static void main(String[] args) {
        Plate p = new Plate();
        for (int i = 0; i < 10; i++)
            new Thread(new GetThread(p)).start();

        for (int i = 0; i < 10; i++)
            new Thread(new AddThread(p)).start();
    }
}

如果盘子里可以存放多个鸡蛋就这样:

缓冲器容量大于1

package com.example;

import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ProducerAndConsumer {
    public static void main(String[] args) {
        Channel channel = new Channel(10);

        int maximumPoolSize = Runtime.getRuntime().availableProcessors() * 4 + 1;
        int corePoolSize = maximumPoolSize / 2;
        ThreadPoolExecutor executor =
            new ThreadPoolExecutor(corePoolSize, maximumPoolSize, 3, TimeUnit.SECONDS, new LinkedBlockingQueue<>(1024),
                Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());
        executor.allowCoreThreadTimeOut(true);

        for (int i = 0; i < 10; i++) {
            executor.submit(() -> {
                channel.get();
            });
        }

        for (int i = 0; i < 10; i++) {
            executor.submit(() -> {
                channel.put(new Object());
            });
        }

        executor.shutdown();
    }

}

class Channel {

    private final Integer maxSize;
    private final Queue<Object> queue = new LinkedList<>();

    public Channel(int maxSize) {
        this.maxSize = maxSize;
    }

    public void put(Object o) {
        // 模拟生产过程
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        synchronized (queue) {
            while (queue.size() >= maxSize) {
                try {
                    System.out.println("此时盘子里有鸡蛋,生产线程" + Thread.currentThread().getName() + "阻塞");
                    queue.wait();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            queue.add(o);
            System.out.println("生产线程放入一个鸡蛋 现有鸡蛋" + queue.size() + "个");
            queue.notifyAll();
        }

    }

    public Object get() {

        // 模拟消费前的一些过程
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        synchronized (queue) {
            while (queue.isEmpty()) {
                try {
                    System.out.println("此时盘子里没有鸡蛋,消费线程" + Thread.currentThread().getName() + "阻塞");
                    queue.wait();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            Object object = queue.poll();
            queue.notifyAll();
            System.out.println("消费线程取得一个鸡蛋  还剩余鸡蛋" + queue.size() + "个");
            return object;
        }
    }

}

关于上面的锁的问题,其实也可以把 synchronized 加到Channel的put和get方法上。

只是说如果以生产者为例,假定put方法里还包含了一些耗时的前期操作,那么我把锁下移,就能保证那些耗时的前期操作可以不用阻塞直接进行。

不过话又说说回来,put方法里就不应该有别的耗时的操作,put就是为了操作那个队列的,为了简便,直接把synchronized 加到方法层次我觉得也没有什么问题。

 

关于线程通信还有一个似乎是空中网的面试题

地址如下

线程通信_子线程执行5次任务,主线程执行10次任务-CSDN博客

感谢glt

参考资料

http://blog.csdn.net/ghsau/article/details/7433673
http://blog.csdn.net/monkey_d_meng/article/details/6251879
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值