Sobes.tech
Junior — Middle

What is the purpose of the Runnable interface in threads and what role does the run method play in this interface?

sobes.tech AI

Answer from AI

The Runnable interface is used to define a task that should be executed in a separate thread. Its main purpose is to separate the task logic from the thread management mechanism.

The run() method is the only abstract method of the Runnable interface, which describes the code that will be executed when the thread starts. When the thread is started, this method is called.

Example of usage:

Runnable task = new Runnable() {
    @Override
    public void run() {
        System.out.println("Task is running in a separate thread");
    }
};

Thread thread = new Thread(task);
thread.start();

Thus, Runnable allows you to define what exactly the thread should do, and Thread — how to start and manage this thread.

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