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

  1. 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();
  1. 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();
  1. 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.

What methods are used to implement execution threads… - sobes.tech