Junior — Middle
What is the purpose of an object that implements the Runnable interface?
sobes.tech AI
Answer from AI
An object that implements the Runnable interface in Java is designed to encapsulate code that should be executed in a separate thread. The interface contains a single method run(), which describes the task's logic. Such an object can be passed to the constructor of the Thread class to start parallel execution.
Example:
public class MyTask implements Runnable {
@Override
public void run() {
System.out.println("Task is running in a separate thread");
}
}
// Usage
Thread thread = new Thread(new MyTask());
thread.start();