Java application threads of communication: the classic example: the producer / consumer problem



/ **
* application thread communication: the classic example: the producer / consumer problem
*
* Producers (Productor) products to the clerk (Clerk), and consumers (Customer) removed the product from the clerk at
* clerk once can only hold a fixed number of products (for example: 20), if producers try to produce more products, clerk
* will be called the producer pause, if there is space to put goods store and then inform the producers to continue production; if the shop there are no products
*, and the clerk will tell consumers wait a minute, if the store has re-notify the consumer product to take away products.
*
* Analysis:
* 1. Is multi-threaded problem? , The producer thread, consumer thread
* 2. Are there any shared data? Yes, the clerk (or product)
* 3. How to solve the security problems thread? Synchronization mechanism, there are three ways
* 4. Are relates to the communication thread? Is
*

* /
class Clerk {

Private ProductCount int = 0;
// produce products
public void produceProduct the synchronized () {

IF (ProductCount <20 is) {
ProductCount ++;
. System.out.println (Thread.currentThread () getName () + " : begin production of the "+ productCount +" products ");

Notify ();

} the else {
// wait for
the try {
the wait ();
} the catch (InterruptedException E) {
e.printStackTrace ();
}
}

}
// consumer
public void consumeProduct the synchronized () {
IF (ProductCount> 0) {
System.out.println (Thread.currentThread () getName () +. ": start spending the first" + productCount + "products");
productCount--;

the Notify ();
} the else {
// wait for
the try {
the wait () ;
} the catch (InterruptedException E) {
e.printStackTrace();
}
}

}
}

class Producer extends Thread{//生产者

private Clerk clerk;

public Producer(Clerk clerk) {
this.clerk = clerk;
}

@Override
public void run() {
System.out.println(getName() + ":开始生产产品.....");

while(true){

try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}

clerk.produceProduct();
}

}
}

class Consumer extends Thread{//消费者
private Clerk clerk;

public Consumer(Clerk clerk) {
this.clerk = clerk;
}

@Override
public void run() {
System.out.println(getName() + ":开始消费产品.....");

while(true){

try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}

clerk.consumeProduct();
}
}
}

public class ProductTest {

public static void main(String[] args) {
Clerk clerk = new Clerk();

Producer p1 = new Producer(clerk);
p1.setName("生产者1");

Consumer c1 = new Consumer(clerk);
c1.setName("消费者1");
Consumer c2 = new Consumer(clerk);
c2.setName("消费者2");

p1.start();
c1.start();
c2.start();

}
}

Guess you like

Origin www.cnblogs.com/wpy188/p/12099899.html