# sleep & yield
# sleep
- 调用 sleep 会让当前线程从 Running 进入 Timed Waiting 状态(阻塞)
- 其它线程可以使用 interrupt 方法打断正在睡眠的线程,这时 sleep 方法会抛出 InterruptedException
- 睡眠结束后的线程未必会立刻得到执行
- 建议用 TimeUnit 的 sleep 代替 Thread 的 sleep 来获得更好的可读性
@Slf4j
public class Demo {
public static void main(String[] args) throws ExecutionException, InterruptedException {
log.info("main run..");
Thread thread = new Thread(() -> {
log.info("thread run..");
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}, "custom-name");
thread.start();
log.info("custom-name state {}", thread.getState());
TimeUnit.MILLISECONDS.sleep(500);
log.info("custom-name state {}", thread.getState());
}
}
//22:57:16.793 [main] INFO com.gao.Demo - main run..
//22:57:16.839 [custom-name] INFO com.gao.Demo - thread run..
//22:57:16.838 [main] INFO com.gao.Demo - custom-name state RUNNABLE
//22:57:17.343 [main] INFO com.gao.Demo - custom-name state TIMED_WAITING
# sleep 打断
@Slf4j
public class Demo {
public static void main(String[] args) throws ExecutionException, InterruptedException {
log.info("main run..");
Thread thread = new Thread(() -> {
log.info("{}", Thread.currentThread().getName() + "run..");
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
log.error(e.getMessage());
throw new RuntimeException(e);
}
}, "custom-thread");
thread.start();
TimeUnit.SECONDS.sleep(2);
thread.interrupt();
}
}
# yield
- 调用 yield 会让当前线程从 Running 进入 Runnable 就绪状态,然后调度执行其它线程
- 具体的实现依赖于操作系统的任务调度器
@Slf4j
public class Demo {
public static void main(String[] args) throws ExecutionException, InterruptedException {
log.info("main run..");
Thread thread = new Thread(() -> {
log.info("{}", Thread.currentThread().getName() + "run..");
try {
Thread.yield();
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
log.error(e.getMessage());
throw new RuntimeException(e);
}
}, "custom-thread");
thread.start();
TimeUnit.SECONDS.sleep(2);
thread.interrupt();
}
}