How two different class threads communicate with each
other?. send example code.

Answer Posted / tulasi prasad

Below I am showing the best example for ur Query.


class Rack
{
int n;
boolean avialable = false;
synchronized int get()
{
if(!avialable )
try
{
wait();
}
catch(InterruptedException e)
{
System.out.println("InterruptedException caught");
}
System.out.println("got:" + n);
avialable = false;
notify();
return n;
}

synchronized int put(int n)
{
if(avialable )
try
{
wait();
}
catch(InterruptedException e)
{
System.out.println("InterruptedException caught");
}
this.n = n;
avialable = true;
System.out.println("put:" + n);
notify();
return n;
}
}

class Producer implements Runnable
{
Rack k;
Producer(Rack k)
{
this.k = k;
new Thread(this, "Producer").start();
}
public void run()
{
int i = 1;
while(true)
{
k.put(i++);
}
}
}
class Consumer implements Runnable
{
Rack k;
Consumer(Rack k)
{
this.k = k;
new Thread(this, "Consumer").start();
}
public void run()
{
while(true)
{
k.get();
}
}
}
class ProducerConsumerProblem
{
public static void main(String args[])
{
Rack k = new Rack();
new Producer(k);
new Consumer(k);
System.out.println("press control - c to stop. ");
}
}

Is This Answer Correct ?    1 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

What is the simpletimezone class in java programming?

859


What is slash r?

788


Is null an object in java?

809


In which order the iterator iterates over collection?

803


What are the types of collections in java?

814


What is the difference between and ?

717


Is zero a positive integer?

798


why are wait(), notify() and notifyall() methods defined in the object class? : Java thread

775


What does the “final” keyword mean in front of a variable? A method? A class?

797


How many types of memory areas are allocated by JVM in java?

822


What is tcp and udp?

810


Why is static used?

795


What is a generic data type?

775


List some oops concepts in java?

818


How do you declare an empty string?

874