Java Reference
In-Depth Information
}
}
The part that may seem strange is using list instead of the main class as the synchronization
target. Each object has its own wait queue, so it does matter which object you use. In theory,
any object can be used as long as your synchronized target and the object in which you run
wait() and notify() are one and the same. Of course, it is good to refer to the object that
you are protecting from concurrent updates, so I used list here.
Hopefully, you're now wondering what this has to do with thread synchronization. There is
only one thread, but the program seems to work:
> javac +E -d . threads.ProdCons1.java
> java ProdCons1
pppccc
List size now 1
List size now 2
List size now 3
Consuming object java.lang.Object@d9e6a356
List size now 2
Consuming object java.lang.Object@d9bea356
List size now 1
Consuming object java.lang.Object@d882a356
List size now 0
But this program is not quite right. If I enter even one more c than there are p 's, think about
what happens. The consume() method does a wait() , but it is no longer possible for the
read() to proceed. The program, we say, is deadlocked : it is waiting on something that can
never happen. Fortunately, this simple case is detected by some versions of the Java runtime:
ppccc
List size now 1
List size now 2
Consuming object java.lang.Object@18faf0
List size now 1
Consuming object java.lang.Object@15bc20
List size now 0
Dumping live threads:
'gc' tid 0x1a0010, status SUSPENDED flags DONTSTOP
blocked@0x19c510 (0x1a0010->|)
'finaliser' tid 0x1ab010, status SUSPENDED flags DONTSTOP
blocked@0x10e480 (0x1ab010->|)
Search WWH ::




Custom Search