Program to impement Multithreading by extending Thread class
class OldThread extends Thread { OldThread() { super("DemoThread"); System.out.println("Child Thread:: " + this); // Start run method 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 Odd Number Thread::3 Even Number Thread::4 Odd Number Thread::5 Even Number Thread::6 Odd Number Thread::7 Even Number Thread::8 Odd Number Thread::9 Even Number Thread::10 Even Number Thread::12 Odd Number Thread::11 Even Number Thread::14 Odd Number Thread::13 Even Number Thread::16 Odd Number Thread::15 Odd Number Thread::17 Even Number Thread::18 Odd Number Thread::19 Even Number Thread::20 Exiting Child Thread Main Thread Exiting