I am refreshing my knowledge on Java and tried to write a Wait and Notify ( Producer, Consumer) type of multithreaded program. The idea is two have a producer thread that adds data to the array list and notifies the consumer thread which is waiting for on the lock attained by the producer thread. The code is giving output not the expected output.
But What I expected to see is
If you see Both the consumer threads are put on wait. When the 1st producer thread adds a data into the arraylist and it sends a notifyall signal to all waiting threads. I parked the Producer thread for 10s so that the waiting thread will have time to pick the array list and display the content of the array. At this point the size of the array should be 1.
package Threads_New;
import java.util.ArrayList;
import java.util.List;
public class Producer_Consumer2 {
List<String> sharedList = new ArrayList();
int count = 0;
Object o = new Object();
public void producer()
{
synchronized (o) {
try {
Thread.sleep(2000);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
System.out.println(Thread.currentThread().getName()
+ "-Adding a value-" + count);
count++;
sharedList.add("Apple-" + count);
o.notifyAll();
System.out.println("The Waiting thread is notified");
try {
Thread.sleep(10000);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
public void consumer() {
System.out.println(Thread.currentThread().getName()
+ "- came inside consumer");
synchronized (o) {
try {
o.wait();
System.out.println(Thread.currentThread().getName()
+ "- Notification recieved");
} catch (InterruptedException ex) {
ex.printStackTrace();
}
System.out.println("I was waiting and now got notified");
for (String s : sharedList) {
System.out.println("Data from the sharedList is:" + s);
}
}
}
public void ThreadStarter() {
Thread[] T = new Thread[3];
int run = 0;
while (run < 2) {
T[run] = new Thread(new Runnable() {
@Override
public void run() {
producer();
}
});
T[run + 1] = new Thread(new Runnable() {
@Override
public void run() {
consumer();
}
});
/*
* for(int i=0;i<10;i++) { t1.start(); t2.start(); }
*/
T[run].start();
T[run + 1].start();
run++;
}
/*
* for(int i=0;i<21;i++) { try{ T[i].join(); T[i+1].join();
* }catch(InterruptedException ex) { ex.printStackTrace(); } }
*/
}
public static void main(String[] args) {
Producer_Consumer2 pc = new Producer_Consumer2();
pc.ThreadStarter();
}
}