Вопрос

I have my own implementation of producer and consumer in java multithreading. But consumer gets the product before producer puts the product. How to overcome this using wait and notify.

package prod;

public class InitProCon {

volatile static int size = 5;

public static void main(String[] args) {
    Consumer con = new Consumer("Consumer Getting", size);
    Producer pro = new Producer("Producer putting", size);
    Thread producer = new Thread(pro);
    Thread consumer = new Thread(con);
    producer.start();
    consumer.start();
}
}


package prod;

public class Product {

static String product;

public void putProduct(String product) {
    Product.product = product;
}

public String getProduct() {
    return product;
}
}




package prod;

public class Consumer implements Runnable {

String cname;
int size;

Consumer(String name, int size) {
    this.cname = name;
    this.size = size;
    System.out.println(cname);
}

@Override
public void run() {
    try {
        for (int i = 0; i < size; i++) {
            Product c = new Product();
            c.getProduct();
            System.out.println("Consumer got product" + i + ""
                    + c.getProduct());
        }
    } catch (Exception e) {
        Thread.currentThread().interrupt();
    }
}
}



package prod;

public class Producer implements Runnable {

String pname;
int size;

Producer(String name, int size) {
    this.pname = name;
    this.size = size;
    System.out.println(pname);
}

@Override
public void run() {
    try {
        for (int i = 0; i < size; i++) {
            Product p = new Product();
            p.putProduct("Consumer product");
            System.out.println("Producer put" + i);
        }
    } catch (Exception e) {
        Thread.currentThread().interrupt();
    }
}
}
Это было полезно?

Решение

You don't have different product contents, you only have one:

package prod;
public class Product {
    static String product;
    public void putProduct(String product) {
        Product.product = product;

Notice the static: All products (Product objects) share the same content. So when your producer produces a new product

        Product p = new Product();
        p.putProduct("Consumer product");

you set the content for all products. So it may seem that the consumers get the same product but that is not quite correct. Every consumer gets a different object of type Product but all products share the same content. By creating the new product you change the content of existing products also. When outputting you can't notice the difference because you only use an artificial index and the shared content (would you use a object specific value like `hashCode´ you could see that those are different objects).

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top