Skip to main content

Inter Thread Communication

class Q
{
   int n;
   boolean valueSet=false;
   synchronized int get()
   {
    if(!valueSet)
    try
    {
     wait();
    }
    catch(InterruptedException e)
    {
     System.out.println("Interrupted Exception caught");
    }
    System.out.println("Got:"+n);
    valueSet=false;
    notify();
    return n;
   }
   synchronized void put(int n)
   { 
   if(valueSet)
   try
   {
    wait();
   }
   catch(InterruptedException e)
   {
    System.out.println("Interrupted Exception caught");
   }
    this.n=n;
    valueSet=true;
   System.out.println("Put:"+n);
   notify();
   }
}
class Producer implements Runnable
{
   Q q;
   Producer(Q q)
   {
    this.q=q;
    new Thread(this,"Producer").start();
   }
   public void run()
   {
    int i=0;
    while(true)
    {
     q.put(i++);
    }
   }
}
class Consumer implements Runnable
{  
 Q q;
 Consumer(Q q)
 {
  this.q=q;
  new Thread(this,"Consumer").start();
 }
 public void run()
 {
  while(true)
  {
   q.get();
  }
 }
}
class ProdCons
{
 public static void main(String[] args)
 {
  Q q=new Q();
  new Producer(q);
  new Consumer(q);
  System.out.println("Press Control-c to stop");
 }
}

Comments

Popular posts from this blog

Find Value of S=ut+1/2*a*t**2.

PROCEDURE:-        1.enter values for u,a,t to find distance        2.find distance with the formulae ut+1/2at 2        3.print the above result CODE:- #include<stdio.h> #include<conio.h> void main() {   float u,t,a,S;   clrscr();   printf(“enter values u,t,a”);   scanf(“%f %f %f”, &u,&t,&a);   S=(u*t)+(0.5*a*t*t);   printf(“\n  S = %f”, S); } Input:- enter values u,t,a               U=10,t=4,a=4.9 Output:- S =79.200