生产者消费者模式

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
使用重入锁未来保证消费和分发任务同步
 * Created by yy on 17/2/8.
 */
public class JavaThreadPool {


    public static void main(String[] args) throws InterruptedException {
        JavaThreadPool javaThreadPool = new JavaThreadPool();
        javaThreadPool.production();
        javaThreadPool.consumption();

    }


    //设置阻塞队列容量
    LinkedBlockingDeque<Object> linkedBlockingDeque = new LinkedBlockingDeque<Object>(100);
    //设置线程数量
    ExecutorService pool = Executors.newFixedThreadPool(2);

    /**
     * 生产者
     *
     * @param
     */
    public void production() {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                int i = 0;
                while (true) {
                    i++;
                    try {
                        linkedBlockingDeque.put(i);
                        System.out.println("生产了:" + i);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }
            }
        });
        thread.start();
    }

    final Lock lock = new ReentrantLock();
    final Condition condition_1 = lock.newCondition();
    final Condition condition_2 = lock.newCondition();

    /**
     * 消费者
     */
    public void consumption() throws InterruptedException {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                ThreadGroup group = new ThreadGroup("测试线程组") {
                    public void uncaughtException(Thread t, Throwable e) {
                        System.out.println(t.getName() + ": " + e.getMessage());
                    }
                };

                while (true) {
                    lock.lock();
                    try {
                        Object obj = linkedBlockingDeque.take();
                        pool.execute(new Examples(group, obj, lock, condition_1, condition_2));
                        condition_2.signal();
                        condition_1.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } finally {
                        lock.unlock();
                    }
                }
            }


        });
        thread.start();



        Thread.sleep(2000);

        new Thread(new Runnable() {
            @Override
            public void run() {
                lock.lock();
                try {
                    condition_1.signal();
                } finally {
                    lock.unlock();
                }
            }
        }).start();

    }

}

/**
 * 执行线程
 */
class Examples extends Thread {
    ThreadGroup group;
    Object obj;
    Lock lock;
    Condition condition_1;
    Condition condition_2;

    Examples(ThreadGroup group, Object obj, Lock lock, Condition condition_1, Condition condition_2) {
        this.group = group;
        this.obj = obj;
        this.lock = lock;
        this.condition_1 = condition_1;
        this.condition_2 = condition_2;
    }

    @Override
    public void run() {
        lock.lock();
        try {
            condition_2.await();
            Thread.sleep(1000 * 1);
            System.out.println(group.getName()+": 消费了:" + obj);
            condition_1.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }
}


上面代码存在单线程执行问题:影响执行效率。

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;

/**
 * Created by yuanyong on 17/2/8.
 */
public class JavaThreadPool {


    public static void main(String[] args) throws InterruptedException {
        JavaThreadPool javaThreadPool = new JavaThreadPool();
        javaThreadPool.production();
        javaThreadPool.consumption();

    }


    //设置阻塞队列容量
    LinkedBlockingDeque<Object> linkedBlockingDeque = new LinkedBlockingDeque<Object>(100);
    //设置线程数量
    ExecutorService pool = Executors.newFixedThreadPool(4);

    /**
     * 生产者
     *
     * @param
     */
    public void production() {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                int i = 0;
                while (true) {
                    i++;
                    try {
                        linkedBlockingDeque.put(i);
//                        System.out.println("生产了:" + i);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }
            }
        });
        thread.start();
    }

    

    /**
     * 消费者
     */
    public void consumption() throws InterruptedException {
        new Thread(new Runnable() {
            @Override
            public void run() {
                ThreadGroup group = new ThreadGroup("测试线程组") {
                    public void uncaughtException(Thread t, Throwable e) {
                        System.out.println(t.getName() + ": " + e.getMessage());
                    }
                };

                while (true) {
                        pool.execute(new Examples(group, linkedBlockingDeque));
                }
            }


        }).start();
    }

}

/**
 * 执行线程
 */
class Examples extends Thread {
    ThreadGroup group;
    LinkedBlockingDeque<Object> linkedBlockingDeque;

    Examples(ThreadGroup group,LinkedBlockingDeque<Object> linkedBlockingDeque) {
        this.group = group;
        this.linkedBlockingDeque = linkedBlockingDeque;
    }

    @Override
    public void run() {
        try {
            Integer obj = (Integer) linkedBlockingDeque.take();
            System.out.println("linkedBlockingDeque.size="+linkedBlockingDeque.size());
            Thread.sleep(1000 * 1);
            System.out.println(group.getName()+":"+Thread.currentThread().getName()+": 消费了:" + obj);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } 

    }
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值