Multiple Threads Executing the Same Runnable
What you'll learn: How multiple threads can run the same Runnable instance simultaneously and what that means for shared state.
The Core Idea
When you pass the same Runnable object to multiple Thread constructors, each thread executes the same run method. This means they all share access to the same instance variables inside that Runnable object. It's like having multiple workers (threads) reading from and writing to the same shared notebook (the Runnable's fields) — they can see each other's changes, which creates both opportunities and risks.
How It Works
You create one Runnable instance, then pass it to multiple Thread objects:
Runnable sharedTask = new Runnable() {
private int counter = 0;
public void run() {
for (int i = 0; i < 5; i++) {
counter++;
System.out.println(Thread.currentThread().getName() + " sees counter: " + counter);
}
}
};
Thread t1 = new Thread(sharedTask);
Thread t2 = new Thread(sharedTask);
t1.start();
t2.start();
Both t1 and t2 execute the same run method and modify the same counter variable. The output will show both threads incrementing and reading the shared counter, but the order is unpredictable.
The Shared State Reality
Since both threads access the same counter, their increments interleave unpredictably. One thread might increment while another reads, leading to surprising results. This sharing is powerful but dangerous without proper coordination (which you'll learn later).
Key Takeaway: Multiple threads can execute the same Runnable instance, directly sharing all its instance variables — enabling both collaboration and potential conflicts in concurrent execution.