Wednesday, 10 June 2015

Program, which creates a three thread. One thread display the numbers from 1 to 5, second thread display the square root of that number etc


Code for Program, which creates a three thread. One thread display the numbers from 1 to 5, second thread display the square root of that number etc in Java



 



 
class numbers implements Runnable
{
    Thread t;
    boolean running=true;
    public numbers(String name, int p)
    {
        t=new Thread(this,name);
        t.setPriority(p);
        t.start();
    }
    publicvoid run()
    {
        System.out.println("\n"+t+ " start");
        for(int i=1;i<=5;i++)
        {
            System.out.println(i);
        }
        System.out.println(t+ " exiting");
    }
}
class squareRoot implements Runnable
{
    Thread t;
    boolean running=true;
    public squareRoot(String name,int p)
    {
        t=new Thread(this,name);
        t.setPriority(p);
        t.start();
    }
    publicvoid run()
    {
        System.out.println("\n"+t+ " start");
        for(int i=1;i<=5;i++)
        {
            System.out.println(i*i);
        }
        System.out.println(t+ " exiting");
    }
}


class ThreadPri
{
    publicstaticvoid main(String args[])
    {
        new numbers("Numbers HIGH PRIORITY",Thread.MAX_PRIORITY);
        new squareRoot("Square MIDDLE PRIORITY",Thread.NORM_PRIORITY);
        Thread t=Thread.currentThread();
        t.setPriority(Thread.MIN_PRIORITY);
        t.setName("Cube LOW PRIORITY");
        
        System.out.println("\n"+t+ " start");
        for(int i=1;i<=5;i++)
        {
            System.out.println(i*i*i);
        }
        System.out.println(t+ " exiting");
    }
}
/*
            Output

Thread[Numbers HIGH PRIORITY,10,main] start
1
2
3
4
5
Thread[Numbers HIGH PRIORITY,10,main] exiting

Thread[Square MIDDLE PRIORITY,7,main] start
1
4
9
16
25
Thread[Square MIDDLE PRIORITY,7,main] exiting

Thread[Cube LOW PRIORITY,3,main] start
1
8
27
64
125
Thread[Cube LOW PRIORITY,3,main] exiting

*/

No comments:

Post a Comment