java的Thread.sleep()相当于让线程睡眠,交出CPU,让CPU去执行其他的任务。 但是有一点要非常注意,sleep方法不会释放锁,也就是说如果当前线程持有对某个对象的锁,则即使调用sleep方法,其他线程也无法访问这个对象。看下面这个例子就清楚了:
package nc.com.thread.traditional.example;
/**
* @ClassName: TestSleep
* @Description: TODO(这里用一句话描述这个类的作用)
* @author A18ccms a18ccms_gmail_com
* @date 2015-12-19 下午06:41:58
*
*/
public class TestSleep {
private int i = 10;
private Object object = new Object();
public static void main(String[] args) throws Exception {
TestSleep test = new TestSleep();
MyThread thread1 = test.new MyThread();
MyThread thread2 = test.new MyThread();
thread1.start();
thread2.start();
}
class MyThread extends Thread{
@Override
public void run() {
//只要有一个线程获得了对象锁,则在当获