Advanced Java Programming - Old Questions

Question Answer Details

9. Write down the life cycle of thread. Write a program to execute multiple threads in priority base. [2+3]

5 marks
Asked in 2075

Answer

AI Generated Answer

AI is thinking...

Official Answer

Life Cycle of Thread

thread in Java at any point of time exists in any one of the following states.

  • New:  A new thread begins its life cycle in the new state. It remains in this state until the program starts the thread. It is also referred to as a born thread. In simple words, a thread has been created, but it has not yet been started. A thread is started by calling its start() method.
  • Runnable: The thread is in the runnable state after the invocation of start() method, but the thread scheduler has not selected it to be the running thread. A thread starts life in the Ready-to-run state by calling the start method and wait for its turn. The thread scheduler decides which thread runs and for how long.
  • Running:  When the thread starts executing, then the state is changed to a “running” state. The scheduler selects one thread from the thread pool, and it starts executing in the application.
  • Dead: This is the state when the thread is terminated. The thread is in running state and as soon as it completed processing it is in “dead state”. Once a thread is in this state, the thread cannot even run again.
  • Blocked (Non-runnable state):This is the state when the thread is still alive but is currently not eligible to run. A thread that is blocked waiting for a monitor lock is in this state. A running thread can transit to one of the non-runnable states depending on the situation. A thread remains in a non-runnable state until a special transition occurs. A thread doesn’t go directly to the running state from a non-runnable state but transits first to the Ready-to-run state.

Program to execute multiple threads in priority base


class First extends Thread

{

    @Override

    public void run()

    {

        for (int i = 1; i <= 10; i++)

        {

            System.out.println(i);

        }

    }

}

class Second extends Thread

{

    @Override

    public void run()

    {

        for (int i = 11; i <= 20; i++)

        {

            System.out.println(i);

        }

    }

}

class Third extends Thread

{

    @Override

    public void run()

    {

        for (int i = 21; i <= 30; i++)

        {

            System.out.println(i);

        }

    }

}

public class ThreadPriority

{

    public static void main(String[] args) throws InterruptedException

    {

        Thread t1 = new First();

        Thread t2 = new Second();

        Thread t3 = new Third();

        t1.setPriority(Thread.MAX_PRIORITY);

        t2.setPriority(Thread.MIN_PRIORITY);

        t3.setPriority(Thread.NORM_PRIORITY);

        t1.start();

        t2.start();

        t3.start();

    }

}