Exercise: Producer - Consumer

2009-03-31  来源:本站原创  分类:Java  人气:227 

With regard to Object.wait () and Object.notify () / notifyAll () to use, write a practice.
Producer - Consumer problem: there is a common resource pool Source, producers, production of goods into the resource pool, consumers take items from the resource pool is consumed.
When the resource pool not have the resources (goods) when the producers informed the production of goods into the pool of resources;
When any one producer the production is complete, notify the consumers to spend their articles;
Consumers will have all the resources consumed, and then inform the producers to produce goods;
Long-winded so much, that is produced when there is only one producer can not be two (more) producers continuous production; consumption when the consumer can have multiple consumers continuously.
With this demand on the bar to practice.
Source assume that resource pool is an array of length 30 of the int [] source = new int [30]; / / value [1,2,3 ..., 28,29,30] array value = corresponding subscript +1;
The value of the array is only used to mark, mark this position has placed articles in;
For the first time produced 20 items, then the position is placed array subscript [0,19], the corresponding value is [1,20];
Then the next time (which may be other producers) to place items starting position (subscript) is 20;
Informed consumers to spend, then the consumer spending start position (subscript) is 0;
After the consumer end, if the second has also produced 20 items, then the position is placed array subscript [20,9], the corresponding value is [21,22 .. 29,30,1,2 ... 9 , 10];
Then the next time (which may be other producers) to place items starting position (subscript) is 10; inform consumers to spend, then the consumer spending start position (subscript) is 20;
At this point the resource pool can be imagined as a big round table rotating at the edge of the round-table placed 30 plates, numbered is 0-29;
The direction of rotation through a fixed round-table to the orderly production and consumption of ^ .. ^
Also invited a friend to the JE on the proposals.
Resource pool class:

/**
 *  A resource pool
 * @author mwei
 * @version 1.0
 */
public class Source {
        public static final int CAPACITY=30;
        public static int[] source=new int[CAPACITY]; // Value  [1,2,3...,28,29,30]
        public static int in=0; //the position to set source
        public static int out=0; //the position to get source
        public static final byte[] LOCK=new byte[0];
}

Producer class:

import java.util.Random;

public class Producer implements Runnable{
        public static Random random=new Random();
        public static volatile boolean prun=true; // The semaphore
        private String name;
        public Producer(String name){this.name=name;}
        public String getName(){return name;}
        public void run(){produce();}
        public void produce(){
                while (true) {
                        synchronized (Source.LOCK) {
                                if (prun) {
                                        Source.LOCK.notifyAll();
                                        int planNum = random.nextInt(10) + 15; //  The number of planned production resources, at least  15 ~  24 A
                                        int actualNum = 0;
                                        for (int i = Source.out; i < Source.CAPACITY + Source.out; i++) { //  Find the location of the place resources
                                                int index = i % Source.CAPACITY;
                                                if (Source.source[index] == 0) {
                                                        Source.in = index; //  Find
                                                        break;
                                                }
                                        }
                                        for (int i = 0; i < planNum; i++) { //  Place resource
                                                if (Source.source[Source.in] == 0) {
                                                        actualNum++; //  Statistics on the number of actual place resources
                                                        Source.source[Source.in] = Source.in + 1;
                                                        Source.in = (++Source.in % Source.CAPACITY);
                                                }
                                        }
                                        int total = 0;
                                        for (int i = 0; i < Source.CAPACITY; i++) { //  Statistical resources on the number of total resource pool
                                                if (Source.source[i] != 0)
                                                        total++;
                                        }
                                        System.out.print(this.getName() + "Plan : " + planNum
                                                        + "\t Produce : " + actualNum); //  The amount of output and actual output scheme
                                        System.out.println("\tTotal : " + total + "\tRange : ["
                                                        + Source.out + ","
                                                        + (Source.in + Source.CAPACITY - 1)
                                                        % Source.CAPACITY + "]"); //  The total resources and scope
                                        prun = false; //  Producers only once
                                        Consumer.crun = true;
                                } else {
                                        try {
                                                System.out.println(this.getName() + ".wait();");
                                                Source.LOCK.wait();
                                        } catch (InterruptedException ie) {
                                                ie.printStackTrace();
                                        }
                                }
                        } // end syn
                } // end while
        }
}

Consumer Class

public class Consumer implements Runnable{
        public static final int CONSUME_NUM=4;
        public static volatile boolean crun=false; // The semaphore
        private String name;
        public Consumer(String name){
                this.name=name;
        }
        public String getName(){
                return name;
        }
        public void run(){
                consume();
        }
        public void consume(){
                while (true) {
                        synchronized (Source.LOCK) {
                                if (crun) {
                                        Source.LOCK.notifyAll();
                                        int actualNum = 0;
                                        for (int i = 0; i < CONSUME_NUM; i++) {
                                                if (Source.source[Source.out] != 0) {
                                                        actualNum++;
                                                        Source.source[Source.out] = 0; //  Consumed
                                                        Source.out = (Source.out + 1) % Source.CAPACITY;
                                                } else {
                                                        ; // do nothing
                                                }
                                        }
                                        System.out.println(this.getName() + " : consumes "
                                                        + actualNum);
                                        int total = 0;
                                        for (int i = 0; i < Source.CAPACITY; i++) { //  Statistical resources on the number of total resource pool
                                                if (Source.source[i] != 0)
                                                        total++;
                                        }
                                        if (total == 0) { //  Consumers have the resource consumption and notify producer
                                                crun = false;
                                                Producer.prun = true;
                                        }
                                } else {
                                        try {
                                                System.out.println(this.getName() + ".wait();");
                                                Source.LOCK.wait();
                                        } catch (InterruptedException e) {
                                                e.printStackTrace();
                                        }
                                }
                        } // end syn
                } // end while
        }
}

Test:

/**
 * test 3 producers and 4 consumers
 * @author mwei
 */
public class Test {
        public static void main(String[] args) {
                new Thread(new Producer("P1=>")).start();
                new Thread(new Producer("P2=>")).start();
                new Thread(new Producer("P3=>")).start();
                new Thread(new Consumer("C1=>")).start();
                new Thread(new Consumer("C2=>")).start();
                new Thread(new Consumer("C3=>")).start();
                new Thread(new Consumer("C4=>")).start();            

        }
}

Running as part of the results:

P3=>Plan : 18         Produce : 18   Total : 18      Range : [28,15]
C2=> : consumes 4
C3=> : consumes 4
C1=> : consumes 4
C4=> : consumes 4
P3=>.wait();
C2=> : consumes 2
P2=>Plan : 19         Produce : 19   Total : 19      Range : [16,4]
C3=> : consumes 4
C1=> : consumes 4
C4=> : consumes 4
C2=> : consumes 4
P2=>.wait();
C3=> : consumes 3
C1=>.wait();
C4=>.wait();
C2=>.wait();
C3=>.wait();
P3=>Plan : 18         Produce : 18   Total : 18      Range : [5,22]
P1=>.wait();
P2=>.wait();
C3=> : consumes 4
C1=> : consumes 4
P3=>.wait();
C4=> : consumes 4
C2=> : consumes 4
C3=> : consumes 2
C1=>.wait();
C4=>.wait();
C2=>.wait();
C3=>.wait();
P2=>Plan : 18         Produce : 18   Total : 18      Range : [23,10]
P1=>.wait();
P3=>.wait();
P2=>.wait();
C1=> : consumes 4
C4=> : consumes 4
C3=> : consumes 4
C2=> : consumes 4
C1=> : consumes 2
C4=>.wait();
C3=>.wait();
C2=>.wait();
相关文章
  • Exercise: Producer - Consumer 2009-03-31

    With regard to Object.wait () and Object.notify () / notifyAll () to use, write a practice. Producer - Consumer problem: there is a common resource pool Source, producers, production of goods into the resource pool, consumers take items from the reso

  • The producer consumer model based on BlockingQueue achieve (that is, use type) 2010-03-29

    Producer-Consumer model is undoubtedly an important framework for achieving mode ... Code uses the example: new DemoPC().startup(); //============================ import java.util.Arrays; import java.util.List; public class DemoPC extends ProducerCon

  • Java thread: Concurrent Collaboration - Producer Consumer Model 2010-03-29

    Java thread: Concurrent Collaboration - Producer Consumer Model For the multi-threaded procedures, regardless of any programming language, producers and consumers are the most classic models. Each door is like learning the same programming language,

  • Java threads Study Notes (9) the producer consumer problem 2010-04-29

    Using multiple threads to simulate the producer consumer problem. BlockingQueue used to achieve more convenient and safer. Simulation generated a cook products, consumer spending, when the product is greater than 10 times the number of chefs rest, bu

  • Producer Consumer Model 2010-05-15

    Producer - Consumer problem: multi-thread access to a classic case, that is, object-oriented thinking by analyzing the problem, the problem involves four objects, the producer Procedure, Consumer Consumer, Product Product, Storage WareHouse. Here a s

  • Java design pattern of the producer consumer model 2010-05-30

    Reprinted For multi-threaded procedures, regardless of any programming language, producer and consumer model is the most classic. Like every programming language to learn, like, Hello World! Are the classic example. In fact, accurate that should be "

  • Linux, C to achieve the producer consumer problem 2010-08-09

    Linux, C to achieve the producer consumer problem

  • Producer Consumer explain 2010-08-19

    blazeds 4 Producer Consumer Study Notes Study Notes 3 Explanation in blazeds Message service which was about the message service is to use the publish / subscribe Transfer Mode Producer (Producer) / Consumer (consumer), Producer and Consumer use Mess

  • Producer Consumer example of 2010-08-19

    Producer Consumer example of an article in the (blazeds Study Notes 4 Producer Consumer explain) our rough look at the Flex Message Communication in Consumer Producer components and simple components of theoretical knowledge, this article let us look

  • Design Pattern: Producer Consumer Model 2010-11-10

    Producer Consumer Model and Guarded Suspension pattern is similar, but Guarded Suspension pattern does not limit the length of the buffer, Producer Consumer model assumes that the products placed in a limited length of the buffer (like a product tabl

  • Typical problems achieving multi-threading (the producer consumer problem. Barber problem and philosophers problem) 2011-01-03

    This paper discusses the interaction of three typical multi-threading problem: producer consumer issues, problems and philosophers barber problem. I made the above three issues of basic processing and programming (Ruby & Erlang). Producer of consumer

  • About the producer - consumer issues some thought 2011-03-26

    About the producer - consumer issues some thought Wrote some of the multi-threaded program, go back and re-open "APUE" and "UNP: IPC", feel particularly rewarding. Here a little summary. 1 Definition Producer-Consumer Problem: also kno

  • Blocking queue and the producer - consumer mode (reference) 2010-03-29

    Since the Java5 has been provided by the BlockingQueue is a special queue, it is the support for two additional operations Queue, these two operations are: retrieving element queue becomes non-empty, and the storage element to wait for space to becom

  • Typical problem to achieve multi-thread (the producer consumer problem. Barber problem with philosophers problem) 2011-01-03

    This paper discusses three typical multi-threaded interaction problems: producers of consumer issues, problems and philosopher barber problem. I have three questions on the process and do the basic programming (Ruby & Erlang). Producer-consumer probl

  • java concurrent study notes (b) the producer consumer queue 2010-11-27

    Consumers LiftOffRunner, he will BlockingQueue of objects from each LiftOff launch and run directly through show call run (), use their own threads to run, rather than start a new thread for each task package producer_consumer_Queue; import java.io.B

  • Thread study 2, notify, and wait to achieve the consumer - producer synchronization 2010-07-27

    /* Producer - Consumer problem , Object has students, parents , Bank, ATM teller machines * Implementation, students in schools with money , Money ran out to the ATM withdrawals by bank card , Card, the money taken out of spending money on the card w

  • C + + programming ideas 2011-07-22

    C + + programming ideas Basic information Original title: Thinking in C + + Volume One: Introduction to Standard C + +, & Volume 2: Practical Programming (2nd Edition) Author: (U.S.) Bruce Eckel Chuck Allison Translator: Liuzong Tian Yuan Siu Shan Pa

  • Software engineer must know the concept of the 10 2009-03-01

    35 kilometers wrote "excellent software engineers make the best use of design patterns and diligent code Reconstruction, the preparation of unit testing, and has easy religious pursuit. In addition to these, excellent software engineers but also prof

  • A multi-threaded note 2010-02-01

    A direct successor to thread class, override the RUN method, when the call starts with the start (); package com.Thread; class MyThread extends Thread (/ / inherit Thread class, as the thread implementation class private String name; / / that the nam

  • 123,123,123,213 2010-03-29

    Preparatory Knowledge 1: Producer - Consumer Model. In the same address space of a process implemented within the two threads. The producer thread produces the message, and then are placed in a buffer for consumers thread. Consumer thread reads the messag