Sobes.tech
Junior — Middle

What is the main purpose of the Runnable interface in Java and where is it used?

sobes.tech AI

Answer from AI

The Runnable interface in Java is designed to represent a task that can be executed in a separate thread.

The main goal is to define the run() method, which contains the code to be executed in the new thread.

Applications:

  • Allows creating objects that can be passed to a thread (Thread) to execute asynchronously.
  • Separates the task from the thread management mechanism.

Example of usage:

public class MyTask implements Runnable {
    @Override
    public void run() {
        System.out.println("Task is running in a separate thread");
    }
}

// Starting the thread
Thread thread = new Thread(new MyTask());
thread.start();

Thus, Runnable simplifies multithreading by allowing you to define the work that needs to be performed in parallel.

What is the main purpose of the Runnable interface in… - sobes.tech