two example scenarios:
first:
public synchronized void foo1(){
.....
}
public void foo2(){
.....
}
and the threads loop is:
public void run() {
while (true) {
foo1();
foo2();
}
}
if i run 10 threads, and one of these acquire lock inside foo1()
other threads which want to execute foo1
will wait outside foo1()
or they can loop and execute code inside foo2
?
second:
public void foo1(){
lock.lock();
....
lock.unlock();
}
public void foo2(){
}
and the threads loop is:
public void run() {
while (true) {
foo1();
foo2();
}
}
if i run 10 threads, and one of these acquire lock inside foo1()
, in this case threads which want to execute foo1
are not blocked outside foo1
?
if i run 10 threads, and one of these acquire lock inside foo1() other threads which want to execute foo1 will wait outside foo1() or they can loop and execute code inside foo2?
Assuming they're being called on the same object, they'll all queue up when they need to execute foo1()
. Any that have already finished foo1()
for that iteration can execute foo2()
... but then will queue up again on the next iteration when they need to execute foo1()
.
if i run 10 threads, and one of these acquire lock inside foo1() , in this case threads which want to execute foo1 are not blocked outside foo1?
Well they're not blocked outside foo1()
, but they'll be blocked inside foo1()
.
The only difference you might see between your examples is in terms of the stack trace. Fundamentally in both cases, executing the main chunk of foo1()
requires the thread to own the lock.
(Note that your unlock
call should be in a finally
block.)
See more on this question at Stackoverflow