Two common approaches:
Implement the Runnable interface: This is the standard best practice because it separates the task logic from the thread runner and leaves your class free to extend another parent class.
class MyTask implements Runnable {
@Override
public void run() {
System.out.println("Running via Runnable interface.");
}
}
public class Main {
public static void main(String[] args) {
Thread thread = new Thread(new MyTask());
thread.start(); # Always call start(), not run()
}
}
Using a Lambda Expression
public class Main {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
System.out.println("Running via Lambda expression.");
});
thread.start();
}
}