wait/notify
释放锁吗?
释放。
因为wait一定是在出现同步代码块里,所以,wait的时候,必须释放锁,其他线程才能获取锁执行,然后其他线程执行完成之后再notify这个线程。
sleep
释放锁吗?
不释放。
它的作用只是,让当前线程暂停几秒,即暂时睡眠几秒。
看官方文档API
/**
* Causes the currently executing thread to sleep (temporarily cease
* execution) for the specified number of milliseconds, subject to
* the precision and accuracy of system timers and schedulers. The thread
* does not lose ownership of any monitors.
*
* @param millis
* the length of time to sleep in milliseconds
*
* @throws IllegalArgumentException
* if the value of {@code millis} is negative
*
* @throws InterruptedException
* if any thread has interrupted the current thread. The
* <i>interrupted status</i> of the current thread is
* cleared when this exception is thrown.
*/
public static native void sleep(long millis) throws InterruptedException;
如果时间是0呢?
yield
是否锁吗?
不释放。
作用
是让线程放弃cpu。
官方文档API
/**
* A hint to the scheduler that the current thread is willing to yield
* its current use of a processor. The scheduler is free to ignore this
* hint.
*
* <p> Yield is a heuristic attempt to improve relative progression
* between threads that would otherwise over-utilise a CPU. Its use
* should be combined with detailed profiling and benchmarking to
* ensure that it actually has the desired effect.
*
* <p> It is rarely appropriate to use this method. It may be useful
* for debugging or testing purposes, where it may help to reproduce
* bugs due to race conditions. It may also be useful when designing
* concurrency control constructs such as the ones in the
* {@link java.util.concurrent.locks} package.
*/
public static native void yield();
什么时候恢复呢?
共同点
1.作用
让当前线程暂时停止执行。
2.针对的对象是谁?
都是针对线程,即当前线程。