生产者消费者模型的四种java编程例子(转载)

package producer_customer;  
  
public class ProducerCustomer1 {  
    public static int limit = 10;  
    public static int have = 0;  
    public static int start = 0;  
    Task[] tasklist = new Task[limit];  
  
    class Producer implements Runnable {  
        @Override  
        public void run() {  
            while (true) {  
                synchronized (tasklist) {  
                    if (ProducerCustomer1.have < ProducerCustomer1.limit) {  
                        Task temp = new Task(  
                                "mytest"  
                                        + (ProducerCustomer1.start + ProducerCustomer1.have)  
                                        % ProducerCustomer1.limit+"\t"+Thread.currentThread().getId());  
                          
                        tasklist[(ProducerCustomer1.start + ProducerCustomer1.have)  
                                % ProducerCustomer1.limit] = temp;  
                        ProducerCustomer1.have++;  
                        tasklist.notifyAll();  
                    } else {  
                        try {  
                            tasklist.wait();  
                        } catch (InterruptedException e) {  
                            e.printStackTrace();  
                        }  
                    }  
                }  
            }  
  
        }  
    }  
  
    class Customer implements Runnable {  
        @Override  
        public void run() {  
            while (true) {  
                Task temp = null;  
                synchronized (tasklist) {  
                    if (ProducerCustomer1.have > 0) {  
                        temp = tasklist[ProducerCustomer1.start];  
                        ProducerCustomer1.start = (ProducerCustomer1.start + 1)  
                                % ProducerCustomer1.limit;  
                        ProducerCustomer1.have--;  
                        System.out.println(temp.taskname + ":"  
                                + Thread.currentThread().getId());  
                        tasklist.notifyAll();  
                    } else {  
                        try {  
                            tasklist.wait();  
                        } catch (InterruptedException e) {  
                            e.printStackTrace();  
                        }  
                    }  
  
                }  
            }  
        }  
    }  
  
    class Task {  
        public String taskname;  
        public Task(String taskname) {  
            this.taskname = taskname;  
        }  
    }  
    public static void main(String[] args) {  
        ProducerCustomer1 p = new ProducerCustomer1();  
        Producer producer = p.new Producer();  
        Customer customer = p.new Customer();  
        new Thread(producer).start();  
        new Thread(producer).start();  
        new Thread(producer).start();  
        new Thread(producer).start();  
        new Thread(customer).start();  
        new Thread(customer).start();  
        new Thread(customer).start();  
    }  
}

[java] view plaincopy
package producer_customer;  
  
import java.util.concurrent.locks.Condition;  
import java.util.concurrent.locks.Lock;  
import java.util.concurrent.locks.ReentrantLock;  
  
  
public class ProducerCustomer2 {  
  
    public static int limit = 10;  
    public static int have = 0;  
    public static int start = 0;  
    Task[] tasklist = new Task[limit];  
    private final Lock lock = new ReentrantLock();  
    private final Condition full = lock.newCondition();  
    private final Condition empty = lock.newCondition();  
  
    class Producer implements Runnable {  
        @Override  
        public void run() {  
            while (true) {  
                lock.lock();  
                if (ProducerCustomer2.have < ProducerCustomer2.limit) {  
                    Task temp = new Task(  
                            "mytest"  
                                    + (ProducerCustomer2.start + ProducerCustomer2.have)  
                                    % ProducerCustomer2.limit + "\t"  
                                    + Thread.currentThread().getId());  
                    tasklist[(ProducerCustomer2.start + ProducerCustomer2.have)  
                            % ProducerCustomer2.limit] = temp;  
                    ProducerCustomer2.have++;  
                    empty.signalAll();  
                } else {  
                    try {  
                        full.await();  
                    } catch (InterruptedException e) {  
                        e.printStackTrace();  
                    }  
                }  
                lock.unlock();  
            }  
  
        }  
  
    }  
  
    class Customer implements Runnable {  
        @Override  
        public void run() {  
            while (true) {  
                Task temp = null;  
                lock.lock();  
                if (ProducerCustomer2.have > 0) {  
                    temp = tasklist[ProducerCustomer2.start];  
                    ProducerCustomer2.start = (ProducerCustomer2.start + 1)  
                            % ProducerCustomer2.limit;  
                    ProducerCustomer2.have--;  
                    System.out.println(temp.taskname + ":"  
                            + Thread.currentThread().getId());  
                    full.signalAll();  
                } else {  
                    try {  
                        empty.await();  
                    } catch (InterruptedException e) {  
                        e.printStackTrace();  
                    }  
                }  
                lock.unlock();  
            }  
        }  
    }  
  
    class Task {  
        public String taskname;  
  
        public Task(String taskname) {  
            this.taskname = taskname;  
        }  
    }  
  
    public static void main(String[] args) {  
        ProducerCustomer2 p = new ProducerCustomer2();  
        Producer producer = p.new Producer();  
        Customer customer = p.new Customer();  
        new Thread(producer).start();  
        new Thread(producer).start();  
        new Thread(producer).start();  
        new Thread(producer).start();  
        new Thread(customer).start();  
        new Thread(customer).start();  
        new Thread(customer).start();  
    }  
}

[java] view plaincopy
package producer_customer;  
  
import java.util.concurrent.LinkedBlockingQueue;  
  
public class ProducerCustomer3 {  
    public static int limit = 10;  
    public static int have = 0;  
    public static int start = 0;  
    LinkedBlockingQueue queue = new LinkedBlockingQueue(limit);  
    class Customer implements Runnable {  
        @Override  
        public void run() {  
            while (true) {  
                try {  
                    Tasks ss=queue.take();  
                    System.out.println(ss.taskname+":"+Thread.currentThread().getId());  
                } catch (InterruptedException e) {  
                    e.printStackTrace();  
                }  
            }  
        }  
    }  
  
    class Producer implements Runnable {  
        @Override  
        public void run() {  
            while (true) {  
                Tasks o = new Tasks("test"+Thread.currentThread().getId());  
                 try {  
                    queue.put(o);  
                } catch (InterruptedException e) {  
                    e.printStackTrace();  
                }  
                  
            }  
        }  
    }  
  
    class Tasks {  
        public String taskname;  
  
        public Tasks(String taskname) {  
            this.taskname = taskname;  
        }  
    }  
    public static void main(String[] args) {  
        ProducerCustomer3 p = new ProducerCustomer3();  
        Producer producer = p.new Producer();  
        Customer customer = p.new Customer();  
        new Thread(producer).start();  
        new Thread(producer).start();  
        new Thread(producer).start();  
        new Thread(producer).start();  
        new Thread(customer).start();  
        new Thread(customer).start();  
        new Thread(customer).start();  
    }  
}

[java] view plaincopy
package producer_customer;  
  
import java.util.concurrent.Semaphore;  
  
public class ProducerCustomer4 {  
    Semaphore mutex = new Semaphore(1);// 互斥量  
    Semaphore notfull = new Semaphore(10);  
    Semaphore notempty = new Semaphore(0);  
    String[] array = new String[10];  
    int putptr, takeptr, count = 0;  
  
    class Producer implements Runnable {  
        @Override  
        public void run() {  
            while (true) {  
                try {  
                    notfull.acquire();  
                    mutex.acquire();  
                    if (putptr == array.length)  
                        putptr = 0;  
                    String temp = new String("temp" + ":" + putptr + ":"  
                            + Thread.currentThread().getId());  
                    array[putptr] = temp;  
                    putptr++;  
                    count++;  
                    mutex.release();  
                    notempty.release();  
                } catch (InterruptedException e) {  
                    e.printStackTrace();  
                }  
            }  
        }  
    }  
  
    class Consumer implements Runnable {  
        @Override  
        public void run() {  
            while (true) {  
                try {  
                    notempty.acquire();  
                    mutex.acquire();  
                    if (takeptr == array.length)  
                        takeptr = 0;  
                    System.out.println(array[takeptr] + ":" + takeptr + ":"  
                            + Thread.currentThread().getId());  
                    takeptr++;  
                    count--;  
                    mutex.release();  
                    notfull.release();  
                } catch (InterruptedException e) {  
                    e.printStackTrace();  
                }  
            }  
        }  
    }  
  
    public static void main(String[] args) {  
        ProducerCustomer4 s = new ProducerCustomer4();  
        Producer producer = s.new Producer();  
        Consumer consumer = s.new Consumer();  
        new Thread(producer).start();  
        new Thread(producer).start();  
        new Thread(producer).start();  
        new Thread(consumer).start();  
        new Thread(consumer).start();  
    }  
}

时间: 2024-10-07 23:10:05

生产者消费者模型的四种java编程例子(转载)的相关文章

[Java并发编程实战] 阻塞队列 BlockingQueue(含代码,生产者-消费者模型)

见贤思齐焉,见不贤而内自省也.-<论语> PS: 如果觉得本文有用的话,请帮忙点赞,留言评论支持一下哦,您的支持是我最大的动力!谢谢啦~ Java5.0 增加了两种新的容器类型,它们是指:Queue 和 BlockingQueue.Queue 用来临时保存一组等待处理的元素.BlockingQueue 扩张了 Queue 接口,增加了可阻塞的插入和获取等操作. BlockingQueue 通常运用于一个线程生产对象放入队列,另一个线程从队列获取对象并消费,这是典型的生产者消费者模型. 这里写图

java 多线程并发系列之 生产者消费者模式的两种实现

在并发编程中使用生产者和消费者模式能够解决绝大多数并发问题.该模式通过平衡生产线程和消费线程的工作能力来提高程序的整体处理数据的速度. 为什么要使用生产者和消费者模式 在线程世界里,生产者就是生产数据的线程,消费者就是消费数据的线程.在多线程开发当中,如果生产者处理速度很快,而消费者处理速度很慢,那么生产者就必须等待消费者处理完,才能继续生产数据.同样的道理,如果消费者的处理能力大于生产者,那么消费者就必须等待生产者.为了解决这种生产消费能力不均衡的问题,所以便有了生产者和消费者模式. 什么是生

python并发编程之多进程(二):互斥锁(同步锁)&amp;进程其他属性&amp;进程间通信(queue)&amp;生产者消费者模型

一,互斥锁,同步锁 进程之间数据不共享,但是共享同一套文件系统,所以访问同一个文件,或同一个打印终端,是没有问题的, 竞争带来的结果就是错乱,如何控制,就是加锁处理 part1:多个进程共享同一打印终端 #并发运行,效率高,但竞争同一打印终端,带来了打印错乱 from multiprocessing import Process import os,time def work(): print('%s is running' %os.getpid()) time.sleep(2) print('

Python之路(第三十八篇) 并发编程:进程同步锁/互斥锁、信号量、事件、队列、生产者消费者模型

一.进程锁(同步锁/互斥锁) 进程之间数据不共享,但是共享同一套文件系统,所以访问同一个文件,或同一个打印终端,是没有问题的, 而共享带来的是竞争,竞争带来的结果就是错乱,如何控制,就是加锁处理. 例子 #并发运行,效率高,但竞争同一打印终端,带来了打印错乱 from multiprocessing import Process import os,time def work(): print('%s is running' %os.getpid()) time.sleep(2) print('

Java里的生产者-消费者模型(Producer and Consumer Pattern in Java)

生产者-消费者模型是多线程问题里面的经典问题,也是面试的常见问题.有如下几个常见的实现方法: 1. wait()/notify() 2. lock & condition 3. BlockingQueue 下面来逐一分析. 1. wait()/notify() 第一种实现,利用根类Object的两个方法wait()/notify(),来停止或者唤醒线程的执行:这也是最原始的实现. 1 public class WaitNotifyBroker<T> implements Broker&

Java多线程15:Queue、BlockingQueue以及利用BlockingQueue实现生产者/消费者模型

Queue是什么 队列,是一种数据结构.除了优先级队列和LIFO队列外,队列都是以FIFO(先进先出)的方式对各个元素进行排序的.无论使用哪种排序方式,队列的头都是调用remove()或poll()移除元素的.在FIFO队列中,所有新元素都插入队列的末尾. Queue中的方法 Queue中的方法不难理解,6个,每2对是一个也就是总共3对.看一下JDK API就知道了: 注意一点就好,Queue通常不允许插入Null,尽管某些实现(比如LinkedList)是允许的,但是也不建议. Blockin

【专家坐堂】四种并发编程模型简介

本文来自网易云社区 概述 并发往往和并行一起被提及,但是我们应该明确的是"并发"不等同于"并行" ?       并发 :同一时间 对待 多件事情 (逻辑层面) ?       并行 :同一时间 做(执行) 多件事情 (物理层面) 并发可以构造出一种问题解决方法,该方法能够被用于并行化,从而让原本只能串行处理的事务并行化,更好地发挥出当前多核CPU,分布式集群的能力. 但是,并发编程和人们正常的思维方式是不一样的,因此才有了各种编程模型的抽象来帮助我们更方便,更不容

5 并发编程--队列&amp;生产者消费者模型

1.队列的介绍 进程彼此之间互相隔离,要实现进程间通信(IPC),multiprocessing模块支持两种形式:队列和管道,这两种方式都是使用消息传递的 创建队列的类(底层就是以管道和锁定的方式实现): Queue([maxsize]):创建共享的进程队列,Queue是多进程安全的队列,可以使用Queue实现多进程之间的数据传递. 参数介绍: maxsize是队列中允许最大项数,省略则无大小限制. 但需要明确: 1.队列内存放的是消息而非大数据 2.队列占用的是内存空间,因而maxsize即便

生产者消费者模型Java实现

生产者消费者模型 生产者消费者模型可以描述为: ①生产者持续生产,直到仓库放满产品,则停止生产进入等待状态:仓库不满后继续生产: ②消费者持续消费,直到仓库空,则停止消费进入等待状态:仓库不空后,继续消费: ③生产者可以有多个,消费者也可以有多个: 生产者消费者模型 对应到程序中,仓库对应缓冲区,可以使用队列来作为缓冲区,并且这个队列应该是有界的,即最大容量是固定的:进入等待状态,则表示要阻塞当前线程,直到某一条件满足,再进行唤醒. 常见的实现方式主要有以下几种. ①使用wait()和notif