my dog learned polymorphism
The moose likes Threads and Synchronization and the fly likes run() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "run()" Watch "run()" New topic


Gillian Bladen-Clark

Joined: Dec 13, 2003
Posts: 18
I have just started learning about threads so apologies if this is obvious to you. From what I have read, there are two main ways of using threads
a) define a class as a subclass of thread, override the run() method and call start() to start a thread (which invokes the overridden run() method)
b) define a class as implementing the runnable interface, define run().
From the example I saw, when you use method b), a timer was used but there was no call to start(). The thread seems to commence when you construct an object of your class. So where is the run() method being called from ?
[ January 02, 2004: Message edited by: Gillian Bladen-Clark ]
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

Using method b) something still has to call start(). If you subclass Thread, you can call start() in the constructor of that class to make an auto-starting thread. Anyway, if you see an example where start() is never called, then you probably just need to look a little deeper.

[Jess in Action][AskingGoodQuestions]
Gillian Bladen-Clark

Joined: Dec 13, 2003
Posts: 18
Thanks for your help, Ernest. I guess it must be something in the Timer class that is calling start() - I shall dig a bit deeper as you suggested.
Annekee Dufour
Ranch Hand

Joined: Nov 04, 2003
Posts: 41
If you want a java.util.Timer to execute a job for you, you have to schedule it. The job should be a java.util.TimerTask. The Timer then starts the job at the appropriate moment. If you add more than one TimerTask, they all run in the same Thread.
On the onther hand, the two ways to implement Threads that you learn as a beginner are:
1. extending Thread (call the start method) and
2. implementing Runnable (create a Thread passing the Runnable as a parameter, and call start on that Thread).
This last version has nothing to do with a Timer.
David Crossett
Ranch Hand

Joined: Feb 05, 2003
Posts: 102
I believe I've seen the same thing as you have. In my example, I was missing the run() because I was using an applet. In that scenario, it seems, the start(), stop(), and run() methods of the applet over-ride the same methods of the Runnable interface ( I know stop() is deprecated...)

David Crossett
-nothing important to say, but learnin' plenty-
I agree. Here's the link:
subject: run()
It's not a secret anymore!