Java program on Multithreading by implementing Runnable Example 5

PROGRAM:

class MyThread implements Runnable {
    Thread t;

    MyThread() {
        System.out.println("I'm constructor");
        t = new Thread(this);
        t.start();
    }

    public void run() {
        try {
            for (int i = 1; i <= 5; i++) {
                System.out.println("Thread is running count" + i);
                Thread.sleep(1000);
            }
        } catch (InterruptedException e) {
            System.out.println("Thread Interupped!");
        }
    }
}

class RunnableDemo {
    public static void main(String[] args) {
        MyThread myt = new MyThread();
        System.out.println("I'm main");
        try {
            while (myt.t.isAlive()) {
                System.out.println("Thread is alive");
                Thread.sleep(1500);
            }
        } catch (InterruptedException e) {
            System.out.println("Main thread Interupped!");
        }
    }
}

OUTPUT:

I'm constructor
I'm main
Thread is alive
Thread is running count1
Thread is running count2
Thread is alive
Thread is running count3
Thread is running count4
Thread is alive
Thread is running count5
Thread is alive

Popular Posts