• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
  • Campbell Ritchie
  • Liutauras Vilda
  • Bear Bibeault
  • Jeanne Boyarsky
  • paul wheaton
  • Junilu Lacar
  • Paul Clapham
  • Knute Snortum
Saloon Keepers:
  • Stephan van Hulst
  • Ron McLeod
  • Tim Moores
  • salvin francis
  • Carey Brown
  • Tim Holloway
  • Frits Walraven
  • Vijitha Kumara

consider code on threads  RSS feed

Ranch Hand
Posts: 127
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Everybody

consider the following code:
class MyRunnable implements Runnable
public static void main(String args[])
MyRunnable mr = new MyRunnable();
Thread t = new Thread(mr);
public void start()
public void run()
System.out.println("inside run()");


From the above code i have some queries:
1.why i need to use "Runnable" interface
2.why i need to instantiate "Thread" and why i need to pass class object 'mr' as the argument
3.when i compile the above program iam getting two "inside run()" methods
in the console instead it should print as "abc" and "inside run()"

please anybody help me out..

Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If an object is already a subclass of a parent other than Thread, then it cannot extend Thread because multiple inheritance is not allowed. So instead, the class can implement the Runnable interface. Then a Thread object can be created by passing the Runnable object to the Thread's constructor.

When you call t.start(), this makes the Thread eligible for execution. Then eventually, that Thread's run() method will be called automatically by the (platform-dependent) thread scheduler. If you call run() directly, then the run() method will simply execute in the current thread, rather than as its own thread.

According to the API for Thread.run(), "If this thread was constructed using a separate Runnable run object, then that Runnable object's run method is called; otherwise, this method does nothing and returns." So MyRunnable.run() is called twice: Once as its own thread via t.start(), and once in the current thread via a direct call to t.run().

But note that Runnable.start() is never called here. Runnable does not extend Thread, so start() is not being overridden. In fact, Thread itself implements the Runnable interface.
[ January 05, 2005: Message edited by: marc weber ]
Aaaaaand ... we're on the march. Stylin. Get with it tiny ad.
global solutions you can do in your home or backyard
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!