Home 成长之路 线程休眠Sleep

线程休眠Sleep

0 78

线程休眠:

  • sleep(Time)指定当前线程阻塞的毫秒数
  • sleep存在异常InterruptedException
  • sleep时间达到后线程进入就绪 状态
  • sleep可以模拟网络延时,倒计时等,模拟网络延时可以帮助发现问题
  • 每一个对象都有一个锁,sleep不会释放锁

2. sleep() 与 interrupt()

public static native void sleep(long millis) throws InterruptedException;
public void interrupt();

sleep(long millis): 睡眠指定时间,程序暂停运行,睡眠期间会让出CPU的执行权,去执行其它线程,同时CPU也会监视睡眠的时间,一旦睡眠时间到就会立刻执行(因为睡眠过程中仍然保留着锁,有锁只要睡眠时间到就能立刻执行)。

sleep(): 睡眠指定时间,即让程序暂停指定时间运行,时间到了会继续执行代码,如果时间未到就要醒需要使用interrupt()来随时唤醒
interrupt(): 唤醒正在睡眠的程序,调用interrupt()方法,会使得sleep()方法抛出InterruptedException异常,当sleep()方法抛出异常就中断了sleep的方法,从而让程序继续运行下去
public static void main(String[] args) throws Exception {
Thread thread0 = new Thread(()-> {
try {
System.out.println(new Date() + “\t” + Thread.currentThread().getName() + “\t太困了,让我睡10秒,中间有事叫我,zZZ。。。”);
Thread.sleep(10000);
} catch (InterruptedException e) {
System.out.println(new Date() + “\t” + Thread.currentThread().getName() + “\t被叫醒了,又要继续干活了”);
}
});
thread0.start();

// 这里睡眠只是为了保证先让上面的那个线程先执行
Thread.sleep(2000);

new Thread(()-> {
System.out.println(new Date() + “\t” + Thread.currentThread().getName() + “\t醒醒,醒醒,别睡了,起来干活了!!!”);
// 无需获取锁就可以调用interrupt
thread0.interrupt();
}).start();
}

4. sleep() 与 wait()

① Thread.sleep(long millis): 睡眠时不会释放锁
public static void main(String[] args) throws InterruptedException {
Object lock = new Object();

new Thread(() -> {
synchronized (lock) {
for (int i = 0; i < 5; i++) {
System.out.println(new Date() + “\t” + Thread.currentThread().getName() + “\t” + i);
try { Thread.sleep(1000); } catch (InterruptedException e) { }
}
}
}).start();

Thread.sleep(1000);

new Thread(() -> {
synchronized (lock) {
for (int i = 0; i < 5; i++) {
System.out.println(new Date() + “\t” + Thread.currentThread().getName() + “\t” + i);
}
}
}).start();
}

object.wait(long timeout): 会释放锁

public class SleepWaitTest { public static void main(String[] args) throws InterruptedException { SleepWaitTest object = new SleepWaitTest();

    new Thread(() -> {
        synchronized (object) {
            System.out.println(new Date() + "\t" + Thread.currentThread().getName() + "\t等待打印文件...");
            try {
                object.wait(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(new Date() + "\t" + Thread.currentThread().getName() + "\t打印结束。。。");
        }
    }).start();

	 // 先上面的线程先执行
    Thread.sleep(1000);

    new Thread(() -> {
        synchronized (object) {
            for (int i = 0; i < 5; i++) {
                System.out.println(new Date() + "\t" + Thread.currentThread().getName() + "\t" + i);
            }
        }
    }).start();
}
}

因main方法中Thread.sleep(1000)所以上面的线程Thread-0先被执行,当循环第一次时就会Thread.sleep(1000)睡眠,因为sleep并不会释放锁,所以Thread-1得不到执行的机会,所以直到Thread-0执行完毕释放锁对象lock,Thread-1才能拿到锁,然后执行Thread-1;

原文链接:https://blog.csdn.net/vbirdbest/article/details/81282163

SIMILAR ARTICLES

发表评论

发表评论