Sobes.tech
Senior

How to run a task in a separate thread in Java?

sobes.tech AI

Answer from AI

In Java, there are several approaches to run a task in a separate thread. Here are two main methods:

  1. Inheriting from the Thread class:
class MyTask extends Thread {
    @Override
    public void run() {
        System.out.println("Task is running in a separate thread");
    }
}

public class Main {
    public static void main(String[] args) {
        MyTask task = new MyTask();
        task.start(); // Starts a new thread
    }
}
  1. Implementing the Runnable interface:
class MyTask implements Runnable {
    @Override
    public void run() {
        System.out.println("Task is running in a separate thread");
    }
}

public class Main {
    public static void main(String[] args) {
        Thread thread = new Thread(new MyTask());
        thread.start();
    }
}

For more complex scenarios and thread pool management, it is recommended to use ExecutorService from the java.util.concurrent package:

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Main {
    public static void main(String[] args) {
        ExecutorService executor = Executors.newSingleThreadExecutor();
        executor.submit(() -> {
            System.out.println("Task in a separate thread via ExecutorService");
        });
        executor.shutdown();
    }
}

This approach is convenient for managing thread lifecycle and scaling.