The following source code are used to implement product/consumer pattern, but they don’t work well, and I don’t know how to solve it.
class 1:productor
package test;
import java.util.ArrayList;
import java.util.List;
public class Productor extends Thread {
private List list = null;
public Productor(ArrayList list) {
this.list = list;
}
public synchronized void product() throws InterruptedException {
for (int e = 0; e < 10; e++) {
System.out.println("Add-" + e + " " + System.currentTimeMillis());
list.add(e);
if (list.size() >= 10) {
wait();
} else {
notifyAll();
}
}
}
public void run() {
try {
while(true){
product();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
class 2:Consumer
package test;
import java.util.ArrayList;
import java.util.List;
public class Consumer extends Thread {
private List list = null;
public Consumer(ArrayList list) {
this.list = list;
}
public synchronized void consume() throws InterruptedException {
if (list.size() <= 0) {
wait();
} else {
notifyAll();
}
for (int e = 0; e < list.size(); e++) {
System.out.println("Remove-" + e + " "
+ System.currentTimeMillis());
list.remove(e);
}
}
public void run() {
try {
while(true){
consume();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
class 3:Testing for product/consumer
package test;
import java.util.ArrayList;
public class TestCP {
public static void main(String args[]) throws InterruptedException {
ArrayList product = new ArrayList();
Productor pt = new Productor(product);
Consumer ct = new Consumer(product);
pt.start();
ct.start();
}
}
The output of TestCP is :
Add-0 1340777963967
Add-1 1340777963968
Add-2 1340777963968
Add-3 1340777963968
Add-4 1340777963968
Add-5 1340777963968
Add-6 1340777963968
Add-7 1340777963968
Add-8 1340777963968
Add-9 1340777963968
My intent is that Productor products 10 elements that stored in a list and consumed by Consumer, then Productor products elements again, Consumer consumes again…
Any feedback will be appreciated, thanks.
You wait/notify on the diferent thread not on the list. So the threads are running on their own monitors not on a shared one. Search for “java wait notify” and keep on reading.