I wanted to write multiple threads under one class and found one way of doing it.
public class ThreadExample {
public static void main(String[] arg)
{
Thread one = new Thread() {
public void run() {
try {
Thread.sleep(2000);
} catch(InterruptedException e) {
e.printStackTrace();
}
System.out.println("One");
}
};
Thread two = new Thread() {
public void run() {
System.out.println("Two");
}
};
one.start();
two.start();
}
}
Thing I don’t get here is, I am neither extending the Thread class nor am I implementing the Runnable interface. How do I understand this?
And If the answer is, “I am just creating the object of the Thread class and using it, then why not always do this rather than doing the things mentioned above?
Technically, what you are doing is extending
Thread. You are extending it on the fly with something called an anonymous inner class – to learn more about what that is, start here and read this page plus the next two.What this means is you are creating temporary inline subclasses that have no name, and whose definitions survive only until the method finishes. Why do this rather than create a named subclass of
Threador implementation ofRunnable? It makes sense when the body ofrun()is as simple as the examples above – there’s less typing and fewer.javafiles to keep track of. One-off simple tasks like these are good candidates for anonymous inner class extension ofThread. For major program logic, you probably want to do a full named class implementation in a separate file.In addition, once you’ve gotten good experience with
Thread, I would encourage you to check out thejava.util.concurrentpackage.