




































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!





































public class Example extends Thread { private static int cnt = 0; // shared state public void run() { int y = cnt; cnt = y + 1; } public static void main(String args[]) { Thread t1 = new Example(); Thread t2 = new Example(); t1.start(); t2.start(); } }
static int cnt = 0; t1.run() { int y = cnt; cnt = y + 1; } t2.run() { int y = cnt; cnt = y + 1; } cnt = 0 Start: both threads ready to run. Each will increment the global count. Shared state
static int cnt = 0; t1.run() { int y = cnt; cnt = y + 1; } t2.run() { int y = cnt; cnt = y + 1; } cnt = 0 T1 is pre-empted. T executes, grabbing the global counter value into y. Shared state y = 0 y = 0
static int cnt = 0; t1.run() { int y = cnt; cnt = y + 1; } t2.run() { int y = cnt; cnt = y + 1; } cnt = 1 T2 executes, storing the incremented cnt value. Shared state y = 0 y = 0
static int cnt = 0; t1.run() { int y = cnt; cnt = y + 1; } t2.run() { int y = cnt; cnt = y + 1; } cnt = 0 Start: both threads ready to run. Each will increment the global count. Shared state
static int cnt = 0; t1.run() { int y = cnt; cnt = y + 1; } t2.run() { int y = cnt; cnt = y + 1; } cnt = 1 T1 executes again, storing the counter value Shared state y = 0
static int cnt = 0; t1.run() { int y = cnt; cnt = y + 1; } t2.run() { int y = cnt; cnt = y + 1; } cnt = 1 T1 finishes. T2 executes, grabbing the global counter value into y. Shared state y = 0 y = 1
int y = cnt; cnt = y+1;
static int cnt = 2; t1.run() { int y = cnt; cnt = y * 2; } t2.run() { int y = cnt; cnt = y + 1; }
Avoiding Interference: Synchronization public class Example extends Thread { private static int cnt = 0; static Object lock = new Object(); public void run() { synchronized (lock) { int y = cnt; cnt = y + 1; } } … } Lock , for protecting the shared state Acquires the lock; Only succeeds if not held by another thread Releases the lock
int cnt = 0; t1.run() { synchronized(lock) { int y = cnt; cnt = y + 1; } } t2.run() { synchronized(lock) { int y = cnt; cnt = y + 1; } } Shared state cnt = 0 T1 reads cnt into y y = 0
int cnt = 0; t1.run() { synchronized(lock) { int y = cnt; cnt = y + 1; } } t2.run() { synchronized(lock) { int y = cnt; cnt = y + 1; } } Shared state cnt = 0 T1 is pre-empted. T2 attempts to acquire the lock but fails because it’s held by T1, so it blocks y = 0