Sobes.tech
Junior — Middle

How did you implement thread creation and management in your project?

sobes.tech AI

Answer from AI

In Java, creating and managing threads can be implemented in several ways:

  1. Extending the Thread class and overriding 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 and passing the object to a Thread:
class MyRunnable implements Runnable {
    public void run() {
        System.out.println("Thread via Runnable");
    }
}

Thread t = new Thread(new MyRunnable());
t.start();
  1. Using ExecutorService to manage a thread pool:
ExecutorService executor = Executors.newFixedThreadPool(2);
executor.submit(() -> System.out.println("Task in thread pool"));
executor.shutdown();

In my projects, I most often used ExecutorService because it simplifies thread management, allows reuse, and controls task completion.