Use of Threads in Java - An Illustration

class newthread extends Thread
    {
        newthread()
        {
            super("Demo Thread");
        }
        public void run()
        {
            try
            {
                for(int i=5;i>0;i--)
                {
                    System.out.println("Child Thread : " +i);
                    Thread.sleep(500);
                }
            }
            catch(InterruptedException e)
            {
                System.out.println("Child Interrupted ");
                System.out.println("Child Exiting");
            }
        }
    }
    public class testthread
    {
        public static void main(String args[])
        {
            newthread nt1=new newthread();
            newthread nt2=new newthread();
            newthread nt3=new newthread();
            nt1.setPriority(3);
            nt1.start();
            nt2.setPriority(5);
            nt2.start();
            nt3.setPriority(7);
            nt3.start();
            try
            {
                for(int i=5;i>0;i--)
                {
                    System.out.println("Main Thread :" + i);
                    Thread.sleep(1000);
                }
            }
            catch(InterruptedException e)
            {
                System.out.println("Main Interrupted");
                System.out.println("Main Exiting");
            }
            System.out.println("Priority of Thread 1 : "+nt1.getPriority());
            System.out.println("Priority of Thread 2 : "+nt2.getPriority());
            System.out.println("Priority of Thread 3 : "+nt3.getPriority());
        }
    }



Output :

Child Thread : 5
Child Thread : 5
Main Thread :5
Child Thread : 5
Child Thread : 4
Child Thread : 4
Child Thread : 4
Child Thread : 3
Child Thread : 3
Main Thread :4
Child Thread : 3
Child Thread : 2
Child Thread : 2
Child Thread : 2
Main Thread :3
Child Thread : 1
Child Thread : 1
Child Thread : 1
Main Thread :2
Main Thread :1
Priority of Thread 1 : 3
Priority of Thread 2 : 5
Priority of Thread 3 : 7 

Top