Programming Tips - Java: Best way to make a Java thread

Date: 2013apr30 Update: 2025sep18 Language: Java Q. Java: 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. As shown in this full example:
class Demo { static class MyWonderfulThread extends Thread { @Override public void run() { System.out.println("Hello from the thread"); // Do what you want } } public static void main(String []args) { // We start the thread here MyWonderfulThread thread = new MyWonderfulThread(); thread.start(); // do NOT call run() System.out.println("Hello from main"); } }
Output:
Hello from main Hello from the thread
Compared to other ways, your run() code is indented less. And you can add a constructor with a parameter, like so:
static 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); } } static 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(); }
Use Executor if you want a pool or scheduled thread https://www.javatpoint.com/java-executorservice