sleep() 的作用是让当前线程休眠,即当前线程会从“运行状态”进入到“休眠(阻塞)状态”。sleep()会指定休眠时间,线程休眠的时间会大于/等于该休眠时间;在线程重新被唤醒时,它会由“阻塞状态”变成“就绪状态”,从而等待cpu的调度执行。
示例:
public class SleepLockTest {
private static Object obj = new Object();
static class ThreadC extends Thread{
public ThreadC(String name){
super(name);
}
public void run(){
//获取obj对象的同步锁
synchronized (obj){
try{
for(int i=0; i<5; i++){
System.out.printf("%s: %d\n", this.getName(), i);
if( i%2 == 0){
ThreadC.sleep(1000);
System.out.println("Start sleep…");
}
}
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
ThreadC t1 = new ThreadC("t1");
ThreadC t2 = new ThreadC("t2");
t1.start();
t2.start();
}
}
运行结果:
t1: 0
Start sleep…
t1: 1
t1: 2
Start sleep…
t1: 3
t1: 4
Start sleep…
t2: 0
Start sleep…
t2: 1
t2: 2
Start sleep…
t2: 3
t2: 4
Start sleep…
结果说明:
(01) sleep()则不会释放锁
网友评论