Tuesday, February 5, 2013

thread tester using java


thread tester

import java.io.*;
import java.awt.*;
public class ThreadTester
{
    public static void main(String args[])
    {
        Q q=new Q();
        P p=new P(q);
        C c=new C(q);
        p.start();
        c.start();
        System.out.println("press control -c to stop");
        }
}
class Q
{
    int n;boolean v=false;
    synchronized int get()
    {
        if(!v)
         try
         {
             wait();
         }
         catch(Exception e)
         {
             e.printStackTrace();
             }
        System.out.println("Got"+n);
        v=false;
        notify();
        return n;
        }
    synchronized void put(int n)
    {
        if(v)
            try
            {
                wait();
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
        this.n=n;
        v=true;
        System.out.println("put"+n);
        notify();
    }
}
class P extends Thread
{
    Q q;
    public P(Q q2)
    {
        super("producer");
        q=q2;
    }
    public void run()
    {
        int i=0;
        while(true)
        {
            q.put(i++);
        }
    }
}
class C extends Thread
{
    Q q;
    public  C(Q q2)
    {
      super("consumer");
        q=q2;
    }
    public void run()
    {
        while(true)
        {
            q.get();
        }
    }
}

No comments:

Post a Comment

Leave the comments