Advertisements
Home > Java > Java Program to show Runnable Interface implementation – Q26

Java Program to show Runnable Interface implementation – Q26


Q26: Java Program to create thdemo class which implements Runnable Interface. Main thread prints numbers from 1 to 10 and child thread prints from 1 to 5.

A Runnable Interface should be implemented by any class whose instances are intended to be executed by a Thread. The class must define a method of no arguments called run.

class NewThread implements Runnable{
	
	Thread t;
	
	NewThread(){
		t = new Thread(this, "Demo Thread");
		System.out.println("Child thread: " + this);
		t.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_runnable{

	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.");
		}
	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: