How To Make Threads In Java

new Thread();

Next question?


How to create threaded behaviors in Java?

Answer 1: Extend Thread (this is rarely used):

class MyThread extends Thread {
public void run() { 
// ... 
}
}

(new MyThread()).start();

Answer 2: Implement Runnable:
class MyRunnable implements Runnable {
public void run() { 
// ... 
}
}

(new Thread(new MyRunnable())).start();


The second method should be preferred in almost all situations. Only subclass Thread if you intend to change its behaviour, implement Runnable to provide a run() method for the standard thread class.

Why? Both approaches work equally well.

Runnable is more reusable than Thread. A Runnable interface just tells that a piece of code can be 'run'. So it may be reused, for example, as the result of an action performed on a menu item, a combo box and in a separate timer-invoked thread. If you extend Thread, it will be useful only in that context -- VhIndukumar

I don't understand. Why is Runnable more reusable than Thread? Specializations of Thread can be reused in those contexts as easily as implementations of Runnable.

Runnable is an interface. Thread is a class. If you want a runnable ComboBox, you can get just that. But you cannot inherit from Thread and ComboBox.'

But you don't need a runnable ComboBox for any of the situations listed above. In fact, I've been programming in Java for 7 years and I've never needed a runnable ComboBox.

I've only heard one convincing reason to use Runnable -- for integration with a threading library like DougLea's util.concurrent. See http://gee.cs.oswego.edu/dl/classes/EDU/oswego/cs/dl/util/concurrent/intro.html for more information.


It is also recommendable to name your threads. E.g.:

new Thread(someRunnable, "someRunnable").start();


It's worth pointing out that you can easily make threads to run arbitrary methods using inner classes.

final SomeClass target=someObject;
(new Thread() { public void run() { target.someMethod(); }).start();

This probably qualifies as reaching too deep into the bag of tricks. Bah. Perhaps create the thread in a separate statement from starting it, with an eye to the LawOfDemeter, but otherwise the intent is clear & straightforward. It's as close as you can get to createThread(functionPtr) as you're going to get in Java.


see HowTo


EditText of this page (last edited May 9, 2003) or FindPage with title or text search