Java program on Multithreading by implementing Runnable Example 4

PROGRAM:

class ThreadOne implements Runnable {
    Thread t;

    ThreadOne() {
        System.out.println("I'm One's Consturctor");
        t = new Thread(this);
        t.start();
    }

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

class ThreadTwo implements Runnable {
    Thread t;

    ThreadTwo() {
        System.out.println("I'm Two's Consturctor");
        t = new Thread(this);
        t.start();
    }

    public void run() {
        try {
            for (char i = 'a'; i <= 'd'; i++) {
                System.out.println("Thread " + i + " is running");
                Thread.sleep(1500);
            }
        } catch (InterruptedException e) {
            System.out.println("Thread interrupted!");
        }
    }
}

class RunnableDemo {
    public static void main(String[] args) {
        ThreadOne t1 = new ThreadOne();
        ThreadTwo t2 = new ThreadTwo();
        System.out.println("I'm main");
    }
}

OUTPUT:

I'm One's Consturctor
Thread 1 is running
I'm Two's Consturctor
I'm main
Thread a is running
Thread 2 is running
Thread b is running
Thread 3 is running
Thread 4 is running
Thread c is running
Thread 5 is running
Thread d is running

Popular Posts