I. Waiting and notifying public final void wait () throws InterruptedException
The occurrence of the waiting condition. Public final void wait (long timeout) throws InterruptedException
The occurrence of the waiting condition. If the notification does not occur within the specified time range, it will return. Public final void wait (long timeout, int nanos) throws InterruptedException wait condition occurs. If the notification does not occur within the specified millisecond or nanoseconds in timeout, it will still return.
Public final void Policy ()
The Thread where the notification is waiting. This condition has occurred.
Public final void policyall () notifies all waiting threads that this condition has occurred.
Wait-What is the purpose of the notification mechanism? How does it work?Wait-the notification mechanism is a synchronization mechanism. It is also a communication mechanism: it enables a Thread to communicate with other threads when the specific conditions are met. Wait-the notification mechanism does not specify the specific conditions.Wait-can the notification mechanism replace the synchronized mechanism?No, the wait, y, and notifyAll methods must be called from the synchronized Method block, because they need to ensure that the thread waiting for and notification does not have a race condition.
public class AnimatedCharacterDisplayCanvas extends CharacterDisplayCanvas implements CharacterListener, Runnable { private boolean done = true; private int curX = 0; private Thread timer = null; public AnimatedCharacterDisplayCanvas() { } public AnimatedCharacterDisplayCanvas(CharacterSource cs) { super(cs); } public synchronized void newCharacter(CharacterEvent ce) { curX = 0; tmpChar[0] = (char) ce.character; repaint(); } protected synchronized void paintComponent(Graphics gc) { Dimension d = getSize(); gc.clearRect(0, 0, d.width, d.height); if (tmpChar[0] == 0) return; int charWidth = fm.charWidth(tmpChar[0]); gc.drawChars(tmpChar, 0, 1, curX++, fontHeight); } public synchronized void run() { while (true) { try { if (done) { wait(); } else { repaint(); wait(100); } } catch (InterruptedException ie) { return; } } } public synchronized void setDone(boolean b) { done = b; if (timer == null) { timer = new Thread(this); timer.start(); } if (!done) notify(); } }
What is the difference between sleep and wait?Both the wait and notify methods must be in the synchronous method. The two synchronous methods in a class use the current this as the lock. After the wait method is executed, the current method lock will be released, if it is not released, notify will never be able to obtain the lock and will never be able to execute notify. The sleep method does not release the lock and blocks the current thread until the end of the time specified by sleep.
Waiting-notification mechanism and Synchronization
What are the details of competing conditions in the wait-notification mechanism?1. the first Thread test condition and confirm it needs to wait 2. the second Thread sets this condition 3. the second Thread calls the notify method, which will not be received, because the second Thread has not entered the waiting 4. the first Thread calls the wait method.
How can this potential race condition be solved?The same lock (current object this) is used to call wait and the method that calls notify, and the lock is used to ensure the atomicity of the operation.
If the Thread receives a notification, can the conditions be correctly set?No. Describe the scenario.
Wait (), Policy () and policyall ()When more than one Thread is waiting for a notification, which Thread will receive the notification when notify is called? The Java specification does not define which Thread receives the notification. However, the Object class provides another method called policyall.
Does the noitfyAll method actually wake up all threads?Yes or no. All the waiting threads will be awakened, but they have not yet re-acquired the lock of the object. Therefore, these threads are not executed in parallel: they must all wait for the object lock to be released. Therefore, only one Thread can be executed at a time, and only after the Thread that calls the notifyAll method releases its lock.
Why wake up all threads?1. Multiple Threads are in the waiting status. You cannot specify which one receives the notification. 2. You do not know how many threads are in the waiting status. Simply synchronize the notification and the waiting Thread will handle it by itself.
Waiting-notification mechanism and synchronized Block
public class AnimatedCharacterDisplayCanvas extends CharacterDisplayCanvas implements CharacterListener, Runnable { private boolean done = true; private int curX = 0; private Thread timer = null; private Object doneLock = new Object(); public AnimatedCharacterDisplayCanvas() { } public AnimatedCharacterDisplayCanvas(CharacterSource cs) { super(cs); } public synchronized void newCharacter(CharacterEvent ce) { curX = 0; tmpChar[0] = (char) ce.character; repaint(); } protected synchronized void paintComponent(Graphics gc) { Dimension d = getSize(); gc.clearRect(0, 0, d.width, d.height); if (tmpChar[0] == 0) return; int charWidth = fm.charWidth(tmpChar[0]); gc.drawChars(tmpChar, 0, 1, curX++, fontHeight); } public void run() {synchronized(doneLock) { while (true) { try { if (done) { doneLock.wait(); } else { repaint(); doneLock.wait(100); } } catch (InterruptedException ie) { return; } }} } public void setDone(boolean b) {synchronized(doneLock) { done = b; if (timer == null) { timer = new Thread(this); timer.start(); } if (!done) doneLock.notify();} } }
Ii. four basic functions of the POSIX condition variable: wait (), thimeed_wait (), signal, and broadcast. It directly corresponds to the wait (), wait (long), Y (), and policyall J2SE 5.0 provided by Java and adds the class that provides the conditional variable function. This kind of appetite Lock interface is used together. Because the new interface is separated from the call and lock objects, its usage flexibility is the same as that in other Threading systems.
public class RandomCharacterGenerator extends Thread implements CharacterSource { private static char[] chars; private static String charArray = "abcdefghijklmnopqrstuvwxyz0123456789"; static { chars = charArray.toCharArray(); } private Random random; private CharacterEventHandler handler; private boolean done = true; private Lock lock = new ReentrantLock(); private Condition cv = lock.newCondition(); public RandomCharacterGenerator() { random = new Random(); handler = new CharacterEventHandler(); } public int getPauseTime() { return (int) (Math.max(1000, 5000 * random.nextDouble())); } public void addCharacterListener(CharacterListener cl) { handler.addCharacterListener(cl); } public void removeCharacterListener(CharacterListener cl) { handler.removeCharacterListener(cl); } public void nextCharacter() { handler.fireNewCharacter(this, (int) chars[random.nextInt(chars.length)]); } public void run() { try { lock.lock(); while (true) { try { if (done) { cv.await(); } else { nextCharacter(); cv.await(getPauseTime(), TimeUnit.MILLISECONDS); } } catch (InterruptedException ie) { return; } } } finally { lock.unlock(); } } public void setDone(boolean b) { try { lock.lock(); done = b; if (!done) cv.signal(); } finally { lock.unlock(); } }}
Why use Condition instead of wait and policy? Or the difference between the two?1. Condition is the same as wait because the lock mechanism must be used to ensure synchronization Security (that is, to avoid race conditions. 2. The Lock object cannot be used with the wait and notify methods because these methods have been used internally to implement the Lock Object. Holding the lock object does not mean that the synchronization Lock of the object is held. 3. The Condition object is not like the wait-notification mechanism. It is a different object created. You can create more than one Condition object for each Lock object, which means that we can independently set individual threads or threadgroups.
Condition Method: The occurrence of void await () Wait Condition. Void awaitUniterruptibly () waits for the occurrence of a condition. Unlike await (), its call cannot be interrupted. Void signal () notifies a Thread waiting to use the Condition object that this Condition has occurred. Void signalAll () notifies all threads waiting to use the Condition object that this Condition has occurred.