Click here to Skip to main content
15,896,417 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Java
class MyThread extends Thread
{
 MyThread(Runnable r)
 {
   super(r);
 }
 public void run()
 {
   SOP("my thread runs.");
 }
}

class MyRunnable implements Runnable
{
   public void run()
   {
     SOP("my runnable runs.");
   }
}

public class MyMain
{
public static void main(String[] arg){
 MyThread obj = new MyThread(new MyRunnable());
 obj.start();}
}


which run method will be called and why???
Posted
Updated 31-Jan-13 23:56pm
v3
Comments
E.F. Nijboer 1-Feb-13 5:21am    
Just try it out (java is free you know) and read your school book on this subject.

1 solution

none.

- your code is not valid (SOP???)
- Runnable is an interface (implements not extends - unless MyRunnable is an Interface too, of course.)

and the main reason is that the class MyMain will not run because it does not have main function.


BUT when you modify that to be a valid code (with 3 separate classes!):

Java
public class MyMain {
	public static MyThread oThread = new MyThread(new MyRunnable());

	public static void main(String[] args) {
		oThread.start();
	}

}

Java
class MyThread extends Thread {
	MyThread(Runnable r) {
		super(r);
	}

	@Override
	public void run() {
		System.out.println("my thread runs.");
	}
}

Java
class MyRunnable implements Runnable {
	@Override
	public void run() {
		System.out.print("my runnable runs.");
	}
}


The Thread is running. Why?
Check the code - it's overriding the run() method from the Runnable.
If you remove the run method from the Thread the runnable's run method is getting it's chance to run.

EDIT: struggled a little with the code highlighting...
 
Share this answer
 
v4
Comments
Tamanna9931 1-Feb-13 5:58am    
Sorry for d mistakes, SOP is System.out.println... dnt mind plzz

Thread(Runnable target) constructor invokes the run() method of class of target object,, but is it not applicable in this code???
TorstenH. 1-Feb-13 7:53am    
Not applicable, because MyThread overrides that. The Runnable has no effect due to that.
The run method of the Runnableis only used, when you remove the run function in MyThread.

Please use a IDE like Eclipse or Netbeans and try it yourself. You will figure it much better then.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900