What are the ways to create a thread in Java, and which one should you actually use?
There are three ways, and one of them is the one you should use.
The first way is to extend the class Thread and to write your work in the method run. The second way is to implement the interface Runnable and to give it to a thread. The third way is to implement the interface Callable and to give it to an executor.
So which one should you actually use? The second one, the interface Runnable, and in practice you give it to an executor rather than making a thread yourself.
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Main {
public static void main(String[] args) {
// The work is a separate object from the thread.
Runnable work = new Runnable() {
public void run() {
System.out.println("the work is running");
}
};
// The executor owns the threads.
ExecutorService pool = Executors.newFixedThreadPool(2);
pool.submit(work);
pool.submit(work);
pool.shutdown();
}
}
There are three reasons for that advice.
The first one is that extending the class Thread takes your class away from the people who want to extend it. Your class can only extend one thing, and if it extends Thread then it can never extend anything else.
The second one is that the interface Runnable keeps the task and the thread apart. The same task can be given to a thread, to an executor, or to a thread pool, and the task does not know or care which one it is running on.
The third one is that the executor manages the threads for you. It reuses them, it limits how many run at once, and it shuts them down properly at the end.
The next question in this topic looks at the difference between the two interfaces.