Slip No 12 Q B

Write a program in java which will show lifecycle (creation, sleep, and dead) of a thread. Program should print randomly the name of thread and value of sleep time. The name of the thread should be hard coded through constructor. The sleep time of a thread will be a random integer in the range 0 to 4999.

import java.util.Random;

class LifeThread extends Thread {

    public LifeThread(String name) {
        super(name);   // Hard-coded thread name
        System.out.println("Thread Created: " + getName());
    }

    public void run() {

        try {
            // Generate random sleep time (0 to 4999)
            Random r = new Random();
            int sleepTime = r.nextInt(5000);

            System.out.println("Thread Running: " + getName());
            System.out.println("Thread " + getName() + " sleeping for "
                    + sleepTime + " milliseconds");

            // Thread goes to sleep state
            Thread.sleep(sleepTime);

        } catch (InterruptedException e) {
            System.out.println(e);
        }

        // Thread enters dead state after run() completes
        System.out.println("Thread Dead: " + getName());
    }
}

public class ThreadLifeCycle {

    public static void main(String[] args) {

        // Creation state
        LifeThread t1 = new LifeThread("Thread-One");
        LifeThread t2 = new LifeThread("Thread-Two");
        LifeThread t3 = new LifeThread("Thread-Three");

        // Runnable state
        t1.start();
        t2.start();
        t3.start();
    }
}
Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top