This is the 15th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

Wait and wake up methods for threads

  • inObject.javaIs definedwait(), notify()notifyAll()Interface, such as:
    • Wait () does:
      • Puts the current thread into the wait state
      • Wait () also causes the current thread to release the lock it holds
    • Notify () and notifyAll()
      • Wakes up all threads waiting on the current object
      • Notify () wakes up a single thread
      • NotifyAll () is to wake up all threads
  • Notify (): Wakes up a single thread waiting on this object’s monitor
  • NotifyAll (): Wakes up all threads waiting on the monitor of this object
  • Wait (): To wait or block the current thread until the other threads call notify() or notifyAll() of the object and the current thread is awakened to the ready state
  • Wait (long timeout): To keep the current thread waiting or blocking until other threads call notify() or notifyAll() of the object, or wait longer than the specified time and the current thread is awakened and ready
  • wait(long timeout, int nanos): Keep the current thread waiting or blocking until another thread calls notify() or notifyAll() of the object, or one of the other threads interrupts the current thread, or the wait time exceeds the specified time, and the current thread is awakened to the ready state

Wait () and notify ()

class MyThread extends Thread {
	public MyThread(String name) {
		super(name);
	}

	public viod run(a) {
		synchronized(this) {
			System.out.println(Thread.currentThread().getName() + "Call notify()");
			// Wake up the current wait threadnotify(); }}}public class WaitTest {
	public static void main(String[] args) {
		Thread thread1 = new Thread("thread1");

		synchronized(thread1) {
			try {
				System.out.println(Thread.currentThread().getName() + "Start thread thread1");
				thread1.start();

				System.out.println(Thread.currentThread().getName() + "Call wait() method");
				thread1.wait();

				System.out.println(Thread.currentThread().getName() + "Carry on");
			} catch(InterruptedException e) { e.printStackTrace(); }}}}Copy the code
Main Starts thread thread1 main calls wait() main calls notify() main to continue executionCopy the code

  • The main thread represents the main thread. The thread T1 represents the thread Thread1 started in WaitTest. The lock represents the synchronization lock of the Thread1 object
  • Create Thread thread1 with new Thread(“thread1”). It then acquires the object’s synchronization lock through synchronized(thread1). The thread1.start() method is then called to start thread thread1
  • The main thread performs thread1.wait() to release the “lock on thread1” and enters a “wait or block state “, waiting for threads on thread1 to wake up with notify() or notifyAll()
  • After thread1 runs, synchronized(this) acquires the lock of the current object, and notify() is invoked to wake up the waiting thread on the current object, that is, the main thread
  • When thread1 finishes running, the lock on the current object is released. The main thread then acquires the lock on the Thread object and runs
  • Question: thread1.wait()Should be let threadthread1Wait, but why let the main threadmainWaiting for?
    • Wait () makes the current thread wait, which is the thread running on the CPU
    • Means that although thread1.wait() is the wait() method called by thread thread1, thread.wait() is called at the location where thread.wait() is called

Wait (long timeout) and notify ()

  • Wait (long timeout) causes the current thread to wait and block until other threads call notify() or notifyAll() of the object or until the specified amount of time has elapsed and the current thread is awakened and ready

  • Main executes t1.start() to start thread T1
  • Wait (3000) and the main thread is blocked. Threads that need to use t1 object locks wake up with notify() or notifyAll() or automatically wake up after 3000ms. The main thread is ready to run
  • After thread T1 runs, the loop will run over and over again
  • After a timeout of 3000ms, the main thread main enters the ready state and then the running state

Wait () and notifyAll ()

  • NotifyAll (): Wakes up all threads waiting on the monitor of this object

  • The main thread creates and starts three threads T1, T2, and T3
  • The main thread sleeps for 3 seconds through sleep(3000), during which threads T1, T2, and T3 all run. A running thread executes obj.wait() and waits for the rest of the thread to wake up with notify() or notifyAll()
  • NotifyAll () is used to wake up the waiting threads on OBJ, i.e., waiting threads T1, T2, and t3. Then, after synchronized(obj) of the main thread completes, the main thread releases the OBj lock so that threads T1, T2, and T3 can acquire the OBJ lock and continue running

The problem

  • By what does notify() wake up the wait thread, i.e. by how are wait() and notify() related?
    • Object synchronization lock
  • Why are notify().wait() and other function methods defined in the Object class rather than Thread?
    • Object functions such as wait() and notify() operate on objects like synchronized
    • Wait () causes the current thread to wait because it is in a wait state, so it should release the lock it holds, or the rest of the thread cannot run until it has acquired the lock
    • After a thread calls wait(), it releases the lock it holds and waits for notify() or notifyAll() to wake up
    • The wake-thread, which is responsible for waking up the wake-thread, cannot wake up the wake-thread until it acquires the object’s synchronization lock, that is, the wake-thread’s synchronization lock, and calls notify() or notifyAll(). The waked wait thread enters the ready state and cannot execute immediately. Because the wake-thread still holds the object’s synchronization lock, the waiting thread cannot continue running until the wake-thread releases the object’s synchronization lock
    • In general,notify(),wait(), etc., depend on object synchronization locks, which are held by objects and have one or only one per object. This is why notify(),wait() and other methods are defined in Object rather than Thread