一、sleep()
1、作用
让调用sleep()的线程睡眠(须告知线程要睡多久),线程sleep()就是让出cpu执行权,进入阻塞状态。睡醒以后,线程又会进入就绪状态。
2、释放锁?
sleep()时,线程不释放锁。
二、证明线程sleep()不释放锁?
package about.thread;
public class AboutSleepMethod {
// 锁对象
private byte[] lock = new byte[0];
public void sing() throws InterruptedException {
// 让run里的线程睡眠,测试线程sleep()会不会释放锁
synchronized (lock) {
System.out.println("线程:" + Thread.currentThread().getName() + "准备睡眠!");
for(int i=0; i<3; i++){
Thread.sleep(1 * 1000);
System.out.println(String.valueOf(i));
}
}
System.out.println("线程:" + Thread.currentThread().getName() + "睡眠结束睡眠!");
}
public void walk() {
// 执行run的线程睡眠,测试walk会不会得到执行
System.out.println("线程:" + Thread.currentThread().getName() + ",准备获取锁执行walk中的synchronized代码块");
synchronized (lock) {
System.out.println("线程:" + Thread.currentThread().getName() + "拿到锁,正在执行walk()中的代码块");
}
}
}
// 线程A调用sing()方法
class A implements Runnable {
private AboutSleepMethod aboutSleepMethod;
public A(AboutSleepMethod aboutSleepMethod) {
this.aboutSleepMethod = aboutSleepMethod;
}
@Override
public void run() {
try {
aboutSleepMethod.sing();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
// 线程B调用walk()方法
// 因为A线程拿到锁lock,并睡眠,
// 而sleep()不会让线程A释放lock锁
// 所以B线程会因为拿不到lock锁而无法执行
// walk()方法中synchronized代码块。
// 通过这个试验就证明了线程sleep()不会释放锁
class B implements Runnable {
private AboutSleepMethod aboutSleepMethod;
public B(AboutSleepMethod aboutSleepMethod) {
this.aboutSleepMethod = aboutSleepMethod;
}
@Override
public void run() {
aboutSleepMethod.walk();
}
}
class Run {
public static void main(String[] args) {
AboutSleepMethod aboutSleepMethod = new AboutSleepMethod();
new Thread(new A(aboutSleepMethod), "thread-a").start(); // 启动线程A
new Thread(new B(aboutSleepMethod),"thread-b").start(); // 启动线程B
}
}
网友评论