Advertisements
Home > Java > Java Program to show Multi Thread operation – Q25

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):


Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: