一、线程阻塞之sleep
- 静态方法 static void sleep(long millis),参数是毫秒
- 作用:
让当前线程进入“阻塞状态”,放弃占有CPU时间片,让给其它线程使用;
间隔特定的时间,去执行一段特定的代码
public class ThreadTest {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + ":" + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
二、面试题
- thread.sleep(1000 * 5); 这行代码会让线程thread进入睡眠状态吗
public class ThreadTest {
public static void main(String[] args) {
Thread thread = new MyThread();
thread.setName("MayDay");
thread.start();