Sobes.tech
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:

  1. 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 the start() method, which launches a new thread.
class MyThread extends Thread {
    public void run() {
        System.out.println("Thread started");
    }
}

MyThread t = new MyThread();
t.start();
  1. 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 call start().
class MyRunnable implements Runnable {
    public void run() {
        System.out.println("Thread started");
    }
}

Thread t = new Thread(new MyRunnable());
t.start();
  1. 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();
  1. 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.