Sleep and wait are all methods that cause a thread to suspend execution temporarily, but they are very different. 1.sleep is thread-class thread, which causes the current thread to sleep temporarily and can be placed in any location.
and wait, which waits for the current thread to temporarily discard the object's right to use, and must be placed in a synchronization method or a synchronization block. 2.Sleep when used, the thread does not discard the object's use, that is, it does not release the object lock, so in the synchronization method or the synchronization block use sleep, when one thread accesses, other threads are inaccessible. The
While wait is the release of the object lock, the current thread discards the object's right to use, allowing other threads to access it. 3. When a thread executes the wait method, it requires another thread to invoke Monitor.pulse () or Monitor.pulseall () to wake up or notify the queue that is waiting.
While sleep is temporarily dormant for a certain amount of time, after the time, the automatic recovery runs without the need for additional thread wakeup. Reference code:
Using System;
Using System.Collections.Generic;
Using System.Text;
Using System.Threading;
Namespace ConsoleApplication1 {class Program {static readonly object _locker = new Object ();
static bool _go; static void Main (string[] args) {new Thread (Work). Start (); The new thread will be blocked because _go = = False Console.ReadLine ();
Wait for user input lock (_locker) {Console.WriteLine ("Change blocking condition ..."); _go = true; Change the blocking condition Monitor.pulse (_locker);
Notifies a waiting queue.
Console.WriteLine ("Sleep wait 1 seconds ...");
Thread.Sleep (1000); static void Work () {lock (_locker) {while (!_GO)//As long as the _go field is FA
LSE, just wait.
{Console.WriteLine ("_go field is false, wait ..."); Monitor.Wait (_locker);
While waiting, the lock has been released. } Console.WriteLine ("Awakened"); }
}
}
run the results as shown in figure: