First, two deferred functions, wait and sleep, are used in multiple threads.
Wait is a method in the object class, and sleep is a method in the thread class.
Sleep is a static method in the thread class. Whether it's a sleep method called B in a thread, or a sleep method called a in a B thread, who calls, who sleeps.
The main thing is that after the sleep method call, there is no release lock. So that threads can still be controlled synchronously. Sleep does not yield system resources;
While wait is the thread waiting in the pool to wait, let go of the system resources.
The thread that calls the wait method does not wake itself and requires the thread to call the Notify/notifyall method to wake up all the threads in the pool before it enters the ready queue to wait for the system to allocate resources. The sleep method automatically wakes up, and if you don't have time to wake up, you can use the interrupt method to force the interrupt.
Thread.Sleep (0)//trigger the operating system to immediately re-compete the CPU.
Scope of Use:
Sleep can be used anywhere. Wait,notify,notifyall can only be used in synchronous control methods or in synchronous control blocks.
Sleep must catch an exception, while Wait,notify,notifyall does not need to catch an exception.
The lock keyword can be used to ensure that a block of code finishes running without being interrupted by another thread. It can define a piece of code as a mutex (critical section), where the mutex only allows one thread to go into execution at a time, while other threads must wait. This is achieved by obtaining a mutex for a given object during the code block run. For example, use the lock function when adding tasks below.
Publicvoid AddTask (List<Datahour>datas) { if(datas!= NULL &&Datas.Count > 0) {Lock (_taskqueuelock) { for(intI= 0; I<Datas.Count; I++) {datas[I]. Iaqi=Getiaqi (datas[I]); } _taskqueue.enqueue (Datas); } } }
Wait in multiple threads and sleep in the end who released the lock