Junior — Middle
What methods are used to implement execution threads in software applications?
sobes.tech AI
Answer from AI
In Java, threads can be implemented in several ways:
- Inheriting from the Thread class — create a class that extends Thread and overrides the
run()method.
class MyThread extends Thread {
public void run() {
System.out.println("Thread started");
}
}
MyThread t = new MyThread();
t.start();
- Implementing the Runnable interface — create a class that implements Runnable and pass it to the Thread constructor.
class MyRunnable implements Runnable {
public void run() {
System.out.println("Thread started");
}
}
Thread t = new Thread(new MyRunnable());
t.start();
- Using ExecutorService — a more modern and flexible way to manage threads, allowing the use of a thread pool.
ExecutorService executor = Executors.newFixedThreadPool(2);
executor.submit(() -> System.out.println("Thread via ExecutorService"));
executor.shutdown();
These methods allow creating and managing threads for parallel task execution.