Junior — Middle
How can you create and start a thread in Java?
sobes.tech AI
Answer from AI
In Java, creating and starting a thread can be done in several ways. The main ones are:
- Inheritance from the Thread class:
class MyThread extends Thread {
public void run() {
System.out.println("Thread started");
}
}
public class Main {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start(); // Starting the thread
}
}
- Implementing the Runnable interface:
class MyRunnable implements Runnable {
public void run() {
System.out.println("Thread started");
}
}
public class Main {
public static void main(String[] args) {
Thread thread = new Thread(new MyRunnable());
thread.start(); // Starting the thread
}
}
- Using lambda expressions (since Java 8):
public class Main {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
System.out.println("Thread started");
});
thread.start();
}
}
The start() method launches a new thread that executes the code in the run() method. It is important not to call run() directly, as that would execute the code in the current thread.