MultiThreading by implementing Runnable interface



Program to implement multithreading by using Runnable interface

class OldThread implements Runnable {
    Thread t;
    OldThread() {
        t = new Thread(this, "DemoThread");
        System.out.println("Child Thread:: " + t);
        // Start run method
        t.start();
    }
    public void run() {
        try {
            for (int i = 2; i <= 20; i += 2) {
                System.out.println("Even Number Thread:: " + i);
                Thread.sleep(500);
            }
        } catch (Exception e) {
            System.out.println("Child Interrupted");
        }
        System.out.println("Exiting Child Thread");
    }
}
class ExtendsThread {
    public static void main(String[] args) {
        OldThread ot = new OldThread();
        try {
            for (int i = 1; i < 20; i += 2) {
                System.out.println("Odd Number Thread:: " + i);
                Thread.sleep(500);
            }
        } catch (Exception e) {
            System.out.println("Main Thread Interrupted");
        }
        System.out.println("Main Thread Exiting");
    }
}

OUTPUT::


Child Thread::Thread[DemoThread, 5, main]

Odd Number Thread::1
Even Number Thread::2
Even Number Thread::4
Odd Number Thread::3
Even Number Thread::6
Odd Number Thread::5
Even Number Thread::8
Odd Number Thread::7
Even Number Thread::10
Odd Number Thread::9
Odd Number Thread::11
Even Number Thread::12
Even Number Thread::14
Odd Number Thread::13
Even Number Thread::16
Odd Number Thread::15
Even Number Thread::18
Odd Number Thread::17
Even Number Thread::20
Odd Number Thread::19

Exiting Child Thread

Main Thread Exiting

Previous Post Next Post