Junior — Middle
How can you run a block of code in a different thread instead of the main thread in Java?
sobes.tech AI
Answer from AI
In Java, to run a piece of code in a different thread instead of the main one, you can use the Thread class or the Runnable interface. Classes from java.util.concurrent, such as ExecutorService, are also commonly used.
Example using Thread:
public class Main {
public static void main(String[] args) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("Code is running in another thread");
}
});
thread.start(); // Starting a new thread
}
}
Or using a lambda expression (Java 8+):
new Thread(() -> {
System.out.println("Code is running in another thread");
}).start();
If you need to manage a thread pool, it's better to use ExecutorService:
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(() -> {
System.out.println("Executing in another thread via ExecutorService");
});
executor.shutdown();
Thus, the code that needs to run in another thread is placed in a Runnable or Callable and started via a new thread or a thread pool.