Logo 
Search:

Java Articles

Submit Article
Home » Articles » Java » Networking TechnologyRSS Feeds

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

Posted By: Harriet Hughes     Category: Java     Views: 8819

Write a program, which creates a three thread. One thread display the numbers from 1 to 5, second thread display the square root of that number and third Thread display the cube of that number. Set the priority of each Thread so the number thread run first, square Thread run second and cube thread run last. Create only one class for a Thread.

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

*/
  
Share: 



Harriet Hughes
Harriet Hughes author of 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 is from London, United Kingdom.
 
View All Articles

 
Please enter your Comment

  • Comment should be atleast 30 Characters.
  • Please put code inside [Code] your code [/Code].

 
No Comment Found, Be the First to post comment!