Professional Documents
Culture Documents
synchronized(this){
this.count += value;
}
}
• takes an object as argument "monitor object"
• "code is synchronized on the monitor object"
• 1 thread execution inside a Java block synchronized on the same monitor object
• 1 thread inside of 2 synchronized blocks:
o If 2nd block had been synchronized on other object than this 1 thread at a time had been able to
execute inside each method
public class MyClass {
synchronized(SynchronizedExample.class) {
System.out.println(
Thread.currentThread().getName() +
" step 1: " + param);
try {
Thread.sleep( (long) (Math.random() * 1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(
Thread.currentThread().getName() +
" step 2: " + param);
}
};
thread1.start();
thread2.start();
}
}
• the synchronized block is synchronized on the class object of the class containing the lambda expression
• it could've been synchronized on another object too
6. Example
public class Example {
threadA.start();
threadB.start();
long count = 0;
}
• the synchronized block inside count() calls the count() recursively enter the same synchronized block
multiple times allowed
• however, this may lead to nested monitor lockout