Common:
1. They are the number of milliseconds in a multithreaded environment, you can block specified in the call of the program and returns.
2. wait () and sleep () can () method to interrupt the thread suspended state by interrupt, so that the threads are instantly thrown InterruptedException.
If thread A now wants to end the thread B, the method can invoke the interrupt corresponding to the thread B Thread instance. If at the moment thread B is wait / sleep / join, then thread B will immediately throw InterruptedException, direct return safely to the end of the thread catch () {} in.
Note that, InterruptedException is thrown from within its own thread, not interrupt () method throws. When you call to interrupt a thread (), if the common thread is executing code, then the thread would not throw InterruptedException. However, once the thread into the wait () / sleep () / join (), will immediately throw InterruptedException.
Except that:
1. Each object has a lock to synchronize access control. Synchronized keyword can interact with objects and locks to synchronize threads.
The method of sleep does not release the lock, the lock release wait method, so that other threads may be used or a method of a synchronization control block.
2.wait, notify and notifyAll only synchronous or a synchronous control method for use inside the control block, and can be used anywhere sleep
3.sleep must catch the exception, and wait, notify and notifyAll do not need to catch the exception
② lock: sleep is the most important method is not release the lock, the lock release wait method, so that other threads may be used or a method of a synchronization control block.
sleep not to sell the system resources; wait is waiting to enter the thread pool to wait to sell the system resources, other threads can occupy CPU. General wait time limit will not increase, because you run a resource wait thread is not enough, then it is useless to wait for the other thread calls notify / notifyAll wakes up all the threads waiting in the pool, it will enter the ready queue waiting OS allocates system resources. sleep (milliseconds) can be specified time so it automatically wake up, can only be called if less than interrupt () forcibly interrupted.
Role Thread.sleep (0) is "operating system immediately triggers a re-CPU competition."
③ range: wait, notify, and notifyAll only inside the block synchronization control method for use in a control or synchronization, sleep and may be used anywhere.
synchronized(x){
x.notify()
//或者wait()
}
sleep 和 wait都需要捕获InterruptedException:
public final void wait() throws InterruptedException {
wait(0);
}
public final native void wait(long timeout) throws InterruptedException;
public static native void sleep(long millis) throws InterruptedException;