Archive
Posts Tagged ‘Runnable Interface’
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):
Categories: Java
Java OO Programs, Runnable Interface




