
Q. A producer thread is continuously producing integers. Write a program to save the integers and find the pattern in which the integers are produced. Constraints: 1. Your solution must be thread safe. 2. Stress will be on following coding standards and data structures used.

In the given, one thread is producing data and another is consuming it. The two threads "Producer" and "Consumer" share the synchronized methods of the class "Threads". At the time of program execution, the "put( )" method is invoked through the "Producer" class which increments the variable "num" by 1. After producing 1 by the producer, the method "get( )" is invoked by through the "Consumer" class which retrieves the produced number and returns it to the output.
class Threads {
int val;
boolean value = false;
synchronized int get() {
if(!value)
try {
wait();
} catch(Exception e) {
System.out.println(e);
}
System.out.println("Get: " + val);
value = false;
notify();
return val;
}
synchronized void put(int val) {
if(value)
try {
wait();
}catch(Exception e) {
System.out.println(e);
}
this.val = val;
value = true;
System.out.println("Put: " + val);
notify();
}
}
class Producer implements Runnable {
Threads th;
Producer(Threads th) {
this.th = th;
new Thread(this, "Producer").start();
}
public void run() {
int i = 0;
while(i<=50) {
th.put(i++);
}
}
}
class Consumer implements Runnable {
Threads th;
Consumer(Threads th) {
this.th = th;
new Thread(this, "Consumer").start();
}
public void run() {
while(true) {
th.get();
}
}
}
class Example {
public static void main(String args[]) {
Threads th = new Threads();
new Producer(th);
new Consumer(th);
}
}
For more information, visit the following link:
http://www.roseindia.net/java/thread/InterthreadCommunication.shtml
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.