How does Runnable behave in multithreaded code?

In Java, the Runnable interface is used to define a task that can be executed by a thread. When a class implements the Runnable interface, it must override the run() method, where the code to be executed by the thread will be placed. Multiple threads can be created to run the same instance of a Runnable object, allowing for concurrent execution of tasks. This behavior is essential in multithreaded applications, as it provides a way to perform operations in parallel, improving efficiency and responsiveness.

Here is a simple example of how the Runnable interface can be used in a multithreaded environment:

class MyRunnable implements Runnable {
        @Override
        public void run() {
            for (int i = 0; i < 5; i++) {
                System.out.println(Thread.currentThread().getName() + " is executing task " + i);
                try {
                    Thread.sleep(100); // Simulating work
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public class Main {
        public static void main(String[] args) {
            Thread thread1 = new Thread(new MyRunnable(), "Thread 1");
            Thread thread2 = new Thread(new MyRunnable(), "Thread 2");
            thread1.start();
            thread2.start();
        }
    }

Runnable multithreading Java threads concurrency thread execution