Programming Tips - What's the best way to make a Java thread?

Date: 2013apr30 Language: Java Q. What's the best way to make a Java thread? A. You can declare a thread a number of ways. For a thread of non-trivial size I prefer extending the Thread class. Like this:
class MyWonderfulThread extends Thread { @Override public void run() { // Do what you want } } void startIt() { MyWonderfulThread thread = new MyWonderfulThread(); thread.start(); // do NOT call run() }
Compared to other ways, your run() code is indented less. And you can add a constructor with a parameter, like so:
class MyWonderfulThread extends Thread { String greeting; MyWonderfulThread(String greeting) { super("MyWonderfulThread"); // Optional but nice for debugging this.greeting = greeting; } @Override public void run() { // Do what you want System.out.println(greeting); } } void startIt() { MyWonderfulThread thread = new MyWonderfulThread("hello"); thread.start(); }
However if a thread is very small, I would do it like this:
void startIt() { (new Thread( { @Override public void run() { // Do one thing } })).start(); }