java并发编程学习之线程的生命周期sleep四

26次阅读

共计 751 个字符,预计需要花费 2 分钟才能阅读完成。

sleep

在指定毫秒数内,让正在执行的当前线程进入休眠期。

示例

public class SleepDemo extends Thread {
    @Override
    public void run() {System.out.println(Thread.currentThread().getName() + "-" + System.currentTimeMillis());
        try {Thread.sleep(2000);
        } catch (InterruptedException e) {e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + "-" + System.currentTimeMillis());
    }

    public static void main(String[] args) {SleepDemo demo = new SleepDemo();
        demo.setName("demo");
        demo.start();
        try {System.out.println(Thread.currentThread().getName() + "-" + System.currentTimeMillis());
            Thread.sleep(1000);
            System.out.println(Thread.currentThread().getName() + "-" + System.currentTimeMillis());
        } catch (InterruptedException e) {e.printStackTrace();
        }
    }
}

运行结果如下:

结果可以看出,main 线程的两次时间相差 1000 毫秒,demo 的两次时间相差 2000 毫秒,sleep 只影响自己的线程运行,不影响其他线程。

正文完
 0