Reprint: http://blog.csdn.net/clam_clam/article/details/6803667
The difference between sleep () and wait ()
Multithreading in Java is a preemptive mechanism rather than a time-sharing mechanism. Threads have the following states: Can run, run, block, die. The preemption mechanism refers to having multiple threads in a running state, but only one thread is running. when there are multiple threads accessing the shared data, the threads need to be synchronized. A comparison of several main methods in a thread: method of the thread class: sleep (), yield () Object methods: Wait () and notify () each object has a machine lock to control synchronous access. The Synchronized keyword can interact with the object's machine lock to achieve thread synchronization. because the sleep () method is a method of the thread class, it cannot alter the object's machine lock. So when sleep () is called in a synchronized method, the thread sleeps, but the object's machine lock is not released, and other threads still cannot access the object. The wait () method frees the machine lock while the thread sleeps, and other threads can access the object. The yield () method is to stop the current thread and let the same priority thread run. The yield () method will not work if there are no equal priority threads. a thread-end flag is: the Run () method ends. a machine lock is released as a flag: synchronized block or method end. Wait () method and Notify () method: When a thread executes to the Wait () method (thread hibernation and a release lock), it enters a waiting pool associated with the object, The machine lock of the object is also lost. When it is awakened by a notify () method, the threads in the waiting pool are placed in the lock pool. The thread join () method causes the current thread to stop waiting until another thread that calls the Join method eventuallyCheck. It is important to note that the thread is not necessarily running immediately after it is activated, but instead enters the queue of the running thread.
Common denominator: They are all in multi-threaded environment, can block a specified number of milliseconds at the call of the program, and return.
Different points: thread.sleep (long) can not be reduced by synchronized block, and using Thread.Sleep () will not lose the current thread to any object of the synchronization lock (monitor);
Object.wait (long) must be used in the synchronized block, and after the call loses the monitor for object, the benefit is that it does not affect other threads manipulating the object.
Give a java.util.Timer example to illustrate.
private void Mainloop () {
while (true) {
....
Synchronized (queue) {
.....
if (!taskfired)//Task hasn ' t yet fired; Wait
Queue.wait (Executiontime-currenttime);
}
}
The reason why you should use Queue.wait () instead of Thread.Sleep () is because you temporarily discard the object lock on the queue, allowing other threads to perform some synchronous operations. Such as:
private void Sched (TimerTask task, long time, long period) {
Synchronized (queue) {
...
Queue.add (Task);
}
}
But as mentioned in the previous article, the precondition for using queue.wait (long) is that the sched () action executes for a short time, otherwise if it is long, then queue.wait () will not be able to wake up on time.
(2)
In front of the wait/notify mechanism, thread also has a sleep () static method, which also allows the thread to pause for a while. The difference between sleep and wait is that sleep does not release the lock, and sleep pauses and wait pauses are not the same. Obj.wait causes the thread to enter the waiting set of the Obj object and waits for a wake-up.
But wait () and sleep () can break the thread's suspend state through the interrupt () method, causing the thread to throw interruptedexception immediately.
If thread A wants to end thread B immediately, you can call the interrupt method on the thread instance that corresponds to threads B. If thread B is wait/sleep/join at the moment, thread B will immediately throw interruptedexception, and return directly in catch () {} to safely end the thread.
It is important to note that Interruptedexception is thrown from within the thread itself, not by the interrupt () method. When you call interrupt () on a thread, the thread does not throw interruptedexception at all if it is executing normal code. However, once the thread has entered wait ()/sleep ()/join (), the interruptedexception is immediately thrown.
The Sleep (), suspend (), resume () methods are deprecated, and wait (), notify (), Notifyall () are recommended.
The sleep () method is the method that causes the thread to stop for a period of time. After the sleep interval expires, the thread does not necessarily resume execution immediately. This is because at that point, other threads may be running and not being dispatched to abort execution unless
(a) The "Wake Up" thread has a higher priority.
(b) The running thread is blocked for other reasons.
When wait () is a thread interaction, if the thread makes a wait () call to a synchronization object x, the thread pauses execution, and the object goes into a wait state until it wakes up or waits until the time is up.
When wait () is called, the thread releases the "lock flag" that it occupies, making other synchronized data in the object that the thread resides in can be used by other threads.
Waite () and notify () because they operate on the object's "lock flags," they must be called in the synchronized function or synchronized block. If the call is made in the non-synchronized function or non-synchronized block, the illegalmonitorstateexception exception will occur at run time, although it can be compiled.
(3)
Here is a post I originally saw on the CSDN forum, involving synchronization, wait (), notify () and other concepts of understanding, I try to according to some of the original replies and think in Java related concepts will Wait () and notify () these two methods to dissect a bit, Welcome advice.
The problem is as follows:
file://Analyze This procedure, and explain, focus on synchronized, wait (), notify Thank you!
class threada
{
public static void Main (string[] args)
{
threadb b=new THREADB ();
B.start ();
System.out.println ("B is start ....");
synchronized (b)//What does the B in parentheses mean and what does it do?
{
try
{
System.out.println ("Waiting for B to complete ...");
B.wait ();//What does this sentence mean, who is it to wait?
System.out.println ("Completed.now Back to Main thread");
}catch (interruptedexception e) {}
}
SYSTEM.OUT.PRINTLN ("Total is:" +b.total);
}
}
Class Threadb extends Thread
{
int total;
public void Run ()
{
Synchronized (This)
{
System.out.println ("THREADB is running..");
for (int i=0;i<100;i++)
{
Total +=i;
SYSTEM.OUT.PRINTLN ("Total is" +total);
}
Notify ();
}
}
}
To analyze this program, first understand notify () and wait (), why do not record the thread in the previous days when the two methods are not recorded, because these two methods are not belong to the thread class, but belong to the bottom of the object base class, that is, not only thread, Each object has notify and wait functions, why? Because they are used to manipulate locks, and each object has a lock, the lock is the basis of each object, since the lock is the basis, then the method of locking is the most basic.
Before looking down, it is best to review the Think in Java 14.3.1 Part 3: Wait and notice, that is, wait () and notify.
According to think in Java, "Wait () allows us to put the thread into the" sleep "state while" actively "waiting for the condition to change. And only when a notify () or Notifyall () changes, the thread is awakened and the condition is checked for change ."
Let's explain the sentence.
Wait () allows us to place the thread in the sleep state, which means that wait is also blocking the current thread, which is the same as sleep or suspend. What's the difference between sleep,suspend?
The difference is that "(wait) while" actively "waiting for the condition to change" is critical, and sleep and suspend cannot do it. Because we sometimes need to use synchronization (synchronized) Help to prevent conflicts between threads, and once using synchronization, the object will be locked, That is, to get the object lock, the other threads to use the object lock can only be queued, wait until the synchronization method or the synchronization block of the program all run the opportunity. In the synchronization method and the synchronization block, whether sleep () or suspend () is not possible to unlock itself when called, They're all hogging the lock on the object being used.
Wait can, however, allow the synchronous method or the synchronization block to temporarily discard the object lock, and temporarily give it to someone else who needs an object lock (this should be a block, or thread), which means that the other synchronization methods in the thread object can be called during wait () execution! In other cases (sleep, Suspend, it's impossible.
But notice what I said earlier, just temporarily give up the object lock, temporarily for other threads to use, I wait for the thread still to get this object lock back. Wait what?
Okay, so how do you lock the object back?
The first method is to limit the time borrowed. Setting parameters in Wait (), such as Wait (1000), in milliseconds, indicates that I only borrowed 1 seconds, and after a second, I automatically retracted.
The second way, let the person who borrowed to inform me, he used up, to give back to me. At that moment, I will take it back. Hey, if I set up 1 hours after the recovery, others only spent half an hour on the end, then what?
So how do people tell me? I believe everyone can think of, notify (), this is the last word "and only when a notify () or notifyall () change, the thread will be awakened" means.
Therefore, we can place a wait () and notify () inside any synchronous method or synchronization block, regardless of whether the class is ready for processing involving threading. And in fact, we can only call Wait () and notify () in the synchronization method or the synchronization block.
It's a breeze to explain the procedure above.
Synchronized (b) {...} Define a synchronization block and use B as the resource lock. B.wait () means to temporarily release the lock and block the current thread so that other threads that use the same lock have the opportunity to execute, and the same lock is used here as the B thread itself. This thread will notify the wait thread with notify () after executing to a certain place, the lock has been exhausted and is notify ( After the synchronization block is running, the wait thread can continue executing.
Also note the difference between sleep and yield reference Web page (http://developer.51cto.com/art/201003/189465.htm):
1) Sleep () causes the current thread to go to a standstill, so the thread that executes sleep () is definitely not executed for the specified time, and yield () simply returns the current thread back to the executable state, so the thread executing yield () is likely to be executed immediately after entering the executable state.
2) Sleep () allows the thread with the lower priority to be executed, and of course allows the same priority and high priority threads to execute, and yield () can only cause the thread with the same priority to have an opportunity to execute.
How does the volatile keyword work in Java?
When we use the volatile keyword to modify a variable, the thread will read the variable directly and not cache it. This ensures that the variables read by the thread are consistent with the memory.
How do I create a daemon thread?
Using the Setdaemon (true) method of the thread class to set the thread as the daemon thread, it is important to note that this method needs to be called before the start () method is called, or the illegalthreadstateexception exception will be thrown.
What is deadlock (Deadlock)? How do I analyze and avoid deadlocks?
Deadlocks are situations in which more than two threads are permanently blocked, which results in a minimum of two threads and more than two resources.
Parsing deadlocks, we need to look at thread dumps for Java applications. We need to identify the threads that are blocked and the resources they wait for. Each resource has a unique ID, which we can use to find out which threads already have their object locks.
Avoiding nested locks, using locks only where needed and avoiding waiting indefinitely is the usual way to avoid deadlocks
What is atomic manipulation? What are the atomic classes (atomic classes) in the Java Concurrency API?
An atomic operation is an operation task unit that is not affected by other operations. Atomic manipulation is a necessary means of avoiding data inconsistency in a multithreaded environment.
Int++ is not an atomic operation, so when one thread reads its value and adds 1 o'clock, another thread may read the previous one, which raises an error.
In order to solve this problem, it is necessary to ensure that the increment operation is atomic, and we can use synchronous technology to do this before JDK1.5. To the Jdk1.5,java.util.concurrent.atomic package provides an int and a long type of class, which can be automatically guaranteed to be atomic for their operations and do not require synchronous use.
The difference between sleep () and wait ()