import java.util.ArrayList;
import java.util.List;
public class ProduConsumTest {
List list = new ArrayList<>();
static int capacity = 3;
public void Producer() throws InterruptedException {
while(true) {
synchronized (this) {
while (list.size() == capacity)
wait();
int x= (int) (Math.random()*10+2);
list.add(x);
System.out.println("Produced--"+x+"--"+Thread.currentThread().getName());
notify();
Thread.sleep(1000);
}}
}
public void Consumer() throws InterruptedException {
while (true) {
synchronized (this) {
while (list.size()==0) {
wait();
System.out.println("waiting");
}
for (int i=0;i
Main class to Test Same
public class MainProd {
public static void main(String [] args) {
final ProduConsumTest prod = new ProduConsumTest();
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
try {
prod.Producer();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
try {
prod.Consumer();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
t1.start();
t1.setName("Prod");
t2.start();
t2.setName("Consum");
}
}
Here us a Producer consumer solution using BlockingQueueProducerConsumer
ConversionConversion EmoticonEmoticon