Java Program to show Multi Thread operation – Q25
Q25: Java Program to create demothread class which extends thread class and main thread prints numbers from 1 to 10 and child thread prints from 1 to 5
A thread is a thread of execution in a program. The Java Virtual Machine allows an application to have multiple threads of execution running concurrently.
class NewThread extends Thread{ NewThread(){ super("Demo Thread"); System.out.println("Child thread: " + this); start(); } public void run(){ try{ for(int i=1; i<=5; i++){ System.out.println("Child Thread: " + i); System.out.println("Child Thread interrupted."); Thread.sleep(500); } } catch(InterruptedException e){ System.out.println("Exiting child thread"); } } } class demo_thread{ public static void main(String args[]){ new NewThread(); try{ for(int i=1; i<=10; i++){ System.out.println("Main Thread: " + i); System.out.println("Main Thread interrupted."); Thread.sleep(500); } } catch(InterruptedException e){ System.out.println("Main thread interrupted in Catch."); } System.out.println("Main Thread exiting"); } }
… from College notes (BCA/MCA assignments):
Categories: Java
Java OO Programs, Multi Threading
Comments (0)
Trackbacks (0)
Leave a comment
Trackback