Junior — Middle
What are the main methods to implement execution flow in programming?
sobes.tech AI
Answer from AI
In Java, the main ways to create a thread of execution:
- Inheriting from the Thread class — create a class that extends Thread and overrides the
run()method. Then, create an object of this class and call thestart()method, which launches a new thread.
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 with a
run()method. Then, create a Thread object passing an instance of Runnable, and callstart().
class MyRunnable implements Runnable {
public void run() {
System.out.println("Thread started");
}
}
Thread t = new Thread(new MyRunnable());
t.start();
- Using Callable and Future — for tasks that return a result and can throw exceptions. Callable is passed to an ExecutorService.
import java.util.concurrent.*;
Callable<Integer> task = () -> {
return 123;
};
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<Integer> future = executor.submit(task);
System.out.println(future.get());
executor.shutdown();
- Using ExecutorService and thread pools — to manage a group of threads and simplify their creation and termination.
These methods cover the main ways to create and manage threads in Java.