Junior — Middle
Have you had experience using the Runnable interface in Java for creating threads or tasks?
sobes.tech AI
Answer from AI
Yes, the Runnable interface in Java is often used for creating threads or tasks. It contains a single method run(), which describes the code to be executed in a separate thread.
Example of using Runnable to create a thread:
class MyTask implements Runnable {
public void run() {
System.out.println("Task is running in thread " + Thread.currentThread().getName());
}
}
public class Main {
public static void main(String[] args) {
Thread thread = new Thread(new MyTask());
thread.start();
}
}
This approach allows separating task logic from thread management, and also using a single Runnable object across different threads if needed.