Junior — Middle
What methods exist for creating and launching threads in an application?
sobes.tech AI
Answer from AI
In Java, there are several ways to create and start a thread (execution thread):
- Extending the Thread class
class MyThread extends Thread {
public void run() {
System.out.println("Thread started");
}
}
MyThread t = new MyThread();
t.start();
- Implementing the Runnable interface
class MyRunnable implements Runnable {
public void run() {
System.out.println("Thread started");
}
}
Thread t = new Thread(new MyRunnable());
t.start();
- Using a lambda expression (Java 8+)
Thread t = new Thread(() -> System.out.println("Thread started"));
t.start();
Starting a thread is done by calling the start() method, which in turn calls the run() method in a new thread.