本节摘要:sleep()功能介绍,sleep()用法示例
一、功能介绍
让当前线程(调用sleep()方法的线程)休息一会,即是让当前线程由运行状态进入到阻塞状态,进而使其他线程有机会继续执行任务。虽然使线程休眠,但是并不释放对象锁,所以说如果在同步块中使用sleep(),其他线程仍然无法获得执行权限。
注意:sleep()方法定义在Thread类中,会调用sleep(millis)这个本地方法,抛出InterruptedException异常,因此需要捕获该异常
二、代码示例
public class SleepDemo {
public static void main(String[] args) {
MyRunnable1 r = new MyRunnable1();
Thread t1 = new Thread(r, "t1");
Thread t2 = new Thread(r, "t2");
t1.start();
t2.start();
}
}
class MyRunnable1 implements Runnable {
@Override
public void run() {
synchronized (this) {
try {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread(