I'm learning about threads and Producer-Consumer model .
I haved copy-paste the code from a book and i have a issue.
When I run the program sometimes the Consumer gets the next number from the buffer even if the producer hasn't put nothing in the buffer.
Example :
Producatorul a pus: 0
Consumatorul a primit: 0
Producatorul a pus: 1
Consumatorul a primit: 1
Producatorul a pus: 2
Consumatorul a primit: 2
Producatorul a pus: 3
Consumatorul a primit: 3
Producatorul a pus: 4
Consumatorul a primit: 4
Producatorul a pus: 5
Consumatorul a primit: 5
Producatorul a pus: 6
Consumatorul a primit: 6
Consumatorul a primit: 7 -Here from where the consumer gets the number ???
Producatorul a pus: 7 -Here is where the producer puts the number,after the consumer has got it already
Producatorul a pus: 8
Consumatorul a primit: 8
Producatorul a pus: 9
Consumatorul a primit: 9
Here are the classes :
Consumer:
class Consumator extends Thread {
private Buffer buffer;
private String mesaj;
public Consumator(Buffer b) {
buffer = b;
}
public void run() {
for (int i = 0; i < 10; i++) {
mesaj = buffer.get();
System.out.println("Consumatorul a primit:\t" + mesaj);
}
}
}
Producer:
class Producator extends Thread {
private Buffer buffer;
private String mesaj;
public Producator(Buffer b) {
buffer = b;
}
public void run() {
for (int i = 0; i < 10; i++) {
buffer.put(""+i);
System.out.println("Producatorul a pus:\t" + i);
try {
sleep((int)(Math.random() * 100));
} catch (InterruptedException e) { }
}
}
}
Buffer:
class Buffer {
private String mesaj="";
private boolean available = false;
public synchronized String get() {
while (!available) {
try {
wait();
//asteapta producatorul sa puna o valoare
} catch (InterruptedException e) { }
}
available = false;
notifyAll();
return mesaj;
}
public synchronized void put(String number) {
while (available) {
try {
wait();
//asteapta consumatorul sa preia valoarea
} catch (InterruptedException e) { }
}
this.mesaj = number;
available = true;
notifyAll();
}
}
TestClas:
public class TestSincronizare1 {
public static void main(String[] args) {
Buffer b = new Buffer();
Producator p1 = new Producator(b);
Consumator c1 = new Consumator(b);
p1.start();
c1.start();
}
}