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 difference between Java1.4 and Java1.5

1825


Which containers use a flowlayout as their default layout in java programming?

504


What is string data?

551


What is loop in java?

525


What are the important features of Java 9 release?

530






What does string intern() method do?

585


What does regex mean?

564


Can I uninstall java?

550


Explain the difference between jvm and jre?

556


In how many ways we can do synchronization in java?

523


What is data structure in java?

529


Why stringbuilder is not thread safe?

538


What is a parameter example?

522


What are packages in java?

561


When does an object becomes eligible for garbage collection in java?

573