Besides the main thread, developers can instantiate their own when:
- A custom class extends the
Threadclass - A
Threadis passed an implementedRunnableinstance
Override the run() method in both cases to define the program to be run concurrently in the new thread, then call the Thread instance's start() method.
public class CustomThread extends Thread {
@Override
public void run() {
// Do something
}
public static void main(String[] args) {
new CustomThread().start();
}
}public class CustomRunnable implements Runnable {
@Override
public void run() {
// Do something
}
public static void main(String[] args) {
new Thread(new CustomRunnable()).start();
}
}new Thread(new Runnable() {
public void run() {
// Do something
}
}).start();new Thread(
() -> { /* Do something */ };
).start();