Archive

Archive for January 13, 2009

Java Program to show Runnable Interface implementation – Q26

January 13, 2009 Leave a comment

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


Advertisement

Java Program to show Multi Thread operation – Q25

January 13, 2009 Leave a comment

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