This article is participating in the Java Theme Month – Java Debug Notes Event, see the event link for details

Q: What is the difference between wait () and sleep ()? ?

What is the difference between wait() and sleep() threads?

Am I aware that the wait()-ing thread is still in running mode and using CPU cycles, but sleep()-ing does not consume any CPU cycles?

Why do we both wait() and sleep() : How do they differ at a lower level?

Answer:


A lot of knowledge points, really need to write out will master ! ! !   \color{purple} a lot of knowledge points, really need to write out just can master!! {~}

Await can be “awakened” by another thread called by the monitor that Notify is waiting for, while sleep cannot. In addition, wait (and notify) must occur in a block of a synchronized monitor object, while sleep does not:

Object mon = ... ; synchronized (mon) { mon.wait(); }Copy the code

At this point, the currently executing thread will wait and release the monitor. Another thread might do it

synchronized (mon) { 
    mon.notify(); 
 }
Copy the code

The first thread (assuming it is the only thread waiting on the monitor) is woken up (on the same MON object).

You can also call notifyAll when multiple threads are waiting on the monitor – this wakes up all threads. However, only one thread will be able to grab the monitor (remember, they wait in a synchronized block) and continue running – then the other threads will block until they can acquire the monitor’s lock.

Another point is that you call wait on the Object itself (that is, on the monitor where you are waiting for the Object), and you call the Thread to sleep.

Another problem is that you can get false awakenings from wait (i.e. threads are waiting for resumes for no apparent reason). In some cases, you should always wait to rotate by following the steps:

synchronized {
    while (!condition) { mon.wait(); }
}
Copy the code

High marks answer

Sleep (N) says: “I have completed the time slice, please do not give me another time slice for at least n milliseconds.” The operating system does not even attempt to schedule dormant threads until the requested time has elapsed.

Yield () says, “I’ve finished the timeslice, but I still have a lot of work to do.” The operating system is free to immediately give another time slice to a thread, or to another thread or to handle a benefit thread that the CPU has abandoned.

Wait () says: “I’ve finished the time slice. Don’t give me another time slice until someone calls Notify ().” As with sleep(), the operating system doesn’t even try to schedule your task unless someone calls notify() (or one of some other wake up situations occurs).

The article translated from yl2gl72eozkinivz3vc6swkesy – ac4c6men2g7xr2a – translate. Translate. Goog/questions / 1…

Sheep does not use CPU,yiedl I always need, wait I do not use CPU.

Excerpt from source short: some core definitions

private volatile String name; // Thread name // Thread priority. The default value is 5, which can be set by yourself. Private Boolean daemon = false; private Boolean daemon = false; /* Private Runnable target; /* private ThreadGroup (); /* private ThreadGroup (); Private ClassLoader contextClassLoader; /* contextClassLoader; /* The inherited AccessControlContext of this thread */ private AccessControlContext inheritedAccessControlContext; Private static int threadInitNumber; private static int threadInitNumber; private static synchronized int nextThreadNum() { return threadInitNumber++; } /* The ThreadLocal value associated with this thread. The mapping by the ref; maintenance. * / ThreadLocal ThreadLocalMap threadLocals = null; /* * The InheritableThreadLocal value associated with this thread. The mapping by InheritreadLableThocal class maintenance. * / ThreadLocal ThreadLocalMap inheritableThreadLocals = null; /* The stack size requested by this thread, or 0 if not specified by the creator. The VM can do whatever * it likes based on this number; */ private long stackSize; /* * Thread ID */ private long tid; Private static long threadSeqNumber; private static long threadSeqNumber; /* Java thread status */ private volatile int threadStatus = 0;Copy the code

Note several important methods:

1. There is a start method, which calls the operating system and uses the operating system to call our run method.

private native void start0();

  1. The interruput method, which is just a flag, does not interrupt immediately

Interrupted() is static: the internal implementation calls isInterrupted() of the current thread and resets the interrupted status of the current thread

IsInterrupted () is an instance method that isInterrupted() for the thread represented by the object calling the method and does not reset the interrupted status of the current thread

  1. Join () blocks the thread by waiting, for example, t1.join() blocks the completion of t1 indefinitely, and continues with the following method.

  2. GetAllStackTraces retrieves stack information for all threads and can be used to extend monitoring.

Other ways you can look at it.

Let’s talk about thread states:

/** Thread state of a thread that has not been started */ NEW, /** thread state of a runnable thread. A runnable thread is executing in the Java Virtual machine, but may be waiting for other resources from the operating system, such as a processor. */ RUNNABLE, /** The thread's thread state is blocked waiting for the monitor to lock. The blocked thread is waiting for the monitor to lock the input synchronized block/method or to re-enter the synchronized block/method after calling Object.wait. While */ / synchronized(this) // {// while (flag) // {// obj.wait(); // BLOCKED, /** * The thread status of the waiting thread. A Thread is in a wait state because one of the following methods is called: Object.wait No timeout Thread.join No timeout locksupport. park The wait state is waiting for another Thread to perform a specific operation. For example, a Thread calling Object.wait () on an Object is waiting for another Thread to call Object.notify (), or an Object.notifyAll () Thread on the Object named Thread.join is waiting for the specified Thread to terminate. */ WAITING, /** The thread state of the WAITING thread with the specified WAITING time. A thread is in a timed wait state because it calls one of the following methods at the specified waiting time: Thread.sleep, object. wait (long) thread. join(long) locksupport. parkNanos locksupport. parkUntil */ TIMED_WAITING, /** Terminates the thread state of the thread. * Thread TERMINATED */ TERMINATED;Copy the code

More understanding, very useful, easy to view the thread stack log.


Welcome to my column S t a c k O v e r F l o w . I select the best questions and answers and test them frequently in interviews ! ! !   \color{red} Welcome to my column StackOverFlow, I will filter the quality of the interview test!! {~}


There are the latest and elegant ways to do this, and I will write my thoughts on this q&A at the end of the article \color{red} has the latest, elegant implementation, and I will also write my opinion on this question at the end of the article {~}

Thank you for reading this, if this article is well written and if you feel there is something to it

Ask for a thumbs up 👍 ask for attention ❤️ ask for share 👥 for 8 abs I really very useful!!

If there are any mistakes in this blog, please comment, thank you very much! ❤ ️ ❤ ️ ❤ ️ ❤ ️