The keyword "synchronized" means that only 1 thread at a time is allowed
through that piece of code. The variable name in parens is the name of
an object that is referred to as the "monitor"; it controls the
synchronization. Thus, in your example, you have 2 blocks:
synchronized (lock1) {
...
}
and
synchronized (lock2) {
...
}
Since these are different monitors, 2 threads can go through the code at
a time (one through each block). However, if both blocks were declared
synchronized (lock1) {
...
}
only one thread could execute one block or the other, but, both blocks
would never be active concurrently.
You might want to go over things further at java.sun.com .
-Java Guy
Chooti Baba wrote:
>
> Hi Gurus,
>
> Please have a look at the following code:
>
> public class MsLunch {
> private long c1 = 0;
> private long c2 = 0;
> private Object lock1 = new Object();
> private Object lock2 = new Object();
>
> public void inc1() {
> synchronized(lock1) {
> c1++;
> }
> }
>
> public void inc2() {
> synchronized(lock2) {
> c2++;
> }
> }
> }
>
> what is the meaning of the following statements:
> synchronized(lock1)
> synchronized(lock2)
>
> I have come across the keyword "synchronized" in blocks/methods,
> but this particular type of "declaration" is confusing me which
> I never came across. Can anyyone please explain me in
> "plain English" the purpose of having a reference within
> brackets next to the keyword "synchronized".
>
> Best Regards & Good Luck
>
> Chooti Baba
>
> [Non-text portions of this message have been removed]
>
>