Example Code:
public class MyClassAt the first look, some questions come to my mind such as;{ private List temp = new ArrayList (); public void addItem(V obj) { synchronized (temp) { while (temp.size() >= maxSize) { temp.wait(); } temp.add(obj); } } public void clear() { synchronized (temp) { temp.clear(); temp.notifyAll(); } } }
1) If "temp"(monitor object) is locked in sychronized block of addItem method, how can processor pass over "synchronized (temp)" in clear method and run "temp.notifyAll()" to wake up monitor object?
Answer: Object.wait() releases the monitor object! Hence, processor can get into synchronized code block in clear method and notify all threads that are put waiting.
2) Is it possible that Object.wait() is used without synchronized block?
Answer: Maybe not in this example above, but the condition in "while" may be set by a separate thread. Hence, synchronization code block is required to have this work correctly.
Hiç yorum yok:
Yorum Gönder