• 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 ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Bear Bibeault
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Knute Snortum
  • Junilu Lacar
  • Devaka Cooray
Saloon Keepers:
  • Ganesh Patekar
  • Tim Moores
  • Carey Brown
  • Stephan van Hulst
  • salvin francis
Bartenders:
  • Ron McLeod
  • Frits Walraven
  • Pete Letkeman

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);
t.start();
t.run();
}
public void start()
{
System.out.println("abc");
}
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..

tx
venkat
 
Sheriff
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 ]
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!