Here is a simple procedure for running a task in a separate thread:
1. Place the code for the task into the "run" method of a class that implements the "Runnable" interface. That interface is very simple, with a single method:
public interface Runnable {
void run();
}
Since "Runnable" is a functional interface, you can make an instance with a lambda expression:
Runnable r = () -> { task code };
2. Construct a "Thread" object from the "Runnable":
Thread t = new Thread(r);
3. Start the thread:
t.start();
NOTE:
You can also define a thread by forming a subclass of the "Thread" class, like this:
class MyThread extends Thread {
public void rund() {
task code
}
}
Then you construct an object of the subclass and call its "start" method. However, this approach is no longer recommended. You decouple the task that is to be run in parrallel from the mechanism of running it. If you have many tasks, it is too expensive to create a separate thread for each of them. Instead, you can use a thread pool.
CAUTION: Do not call the "run" method of the "Thread" class or the "Runnable" object. Calling the "run" method directly merely executes the task in the same thread -- no new thread is started. Instead, call the "Thread.start" method. It create a new thread that executes the "run" method.