As per my understanding we use “synchronized statement” in java to stop the interference between multiple threads.
Now I am trying to understand the significance of expr in following expression.
synchronized (expr) {
statements
}
Because looks like locking behavior depends on expr object.
e.g.
public class Sync extends Thread {
static int [] arr = {0,1,2};
Object lock = new Object();
public static void main(String[] args){
Sync ob1 = new Sync();
Sync ob2 = new Sync();
ob1.start();
ob2.start();
}
@Override
public void run() {
synchronized (arr) {
for(int i = 0;i < arr.length; ++i){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " " + arr[i]);
}
}
}
}
Now in above example when I am using “arr” object in synchronized statement(synchronized (arr) ) I am getting consistently expected output as follows .
Thread-0 0
Thread-0 1
Thread-0 2
Thread-1 0
Thread-1 1
Thread-1 2
But when I using “lock” object in synchronized statement(synchronized (lock)), I am getting output as follows.
Thread-0 0
Thread-1 0
Thread-0 1
Thread-1 1
Thread-0 2
Thread-1 2
Shouldn’t the output be same in both cases.
Thanks,
Shantanu
arr Objectis static in nature, so both thread is share same arr, in case lock isinstance objectit will have two different instance in two thread.So when you synchronize here with arr Object, any thread which enter first into the block that hold the lock of
arr objectand will finish its execution and other will wait until first thread finished or release the lock.In case of lock object it is complete two different object(two resource), so each thread hold the lock of different resource or object, so execution will be parallel.