New Want to Write for Computaholics ? if Yes Contact us at "contact@computaholics.in"

Java Program to implement Interthread Communication

Java Program to implement Interthread Communication:-

class Consumer implements Runnable
{
Counter counter;
Thread t;
Consumer(Counter counter)
{
this.counter = counter;
t = new Thread(this);
t.start();
}
public void run()
{
int i;
while ((i = counter.getValue()) < 50);
}
}
class Counter
{
int value;
boolean valueSet;
Counter()
{
valueSet = false;
}
synchronized void setValue(int value)
{
try
{
if (valueSet == true)
{
wait();
}
this.value = value;
System.out.println("Value produced : " + value);
valueSet = true;
notify();
}
catch (InterruptedException e1){}
}
synchronized int getValue()
{
try
{
if (valueSet == false)
{
wait();
}
System.out.println("Value consumed : " + value);
valueSet = false;
notify();
}
catch (InterruptedException e1){}
return value;
}
}
class Producer implements Runnable
{
Counter counter;
Thread t;
Producer(Counter counter)
{
this.counter = counter;
t = new Thread(this);
t.start();
}
public void run()
{
int i;
for (i=1;i<=50;i++)
counter.setValue(i);
}
}
public class InterThreadComm
{
public static void main(String args[])
{
Counter counter = new Counter();
Producer p = new Producer(counter);
Consumer c = new Consumer(counter);
}
}
Copyright © C Program | Java | OpenGL Programming | Hadoop at Computaholics