介绍

  1. 调用sleep会让当前线程从Running进入Timed Waiting状态
  2. 其他线程可以用interrupt方法打断正在睡眠的线程,这时候sleep方法会输出InterruptedException
  3. 睡眠结束后的线程未必会得到执行
  4. 建议用TimeUnit的sleep代替Thread的sleep获得更好的可读性

package cn.meowrain;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

@Slf4j
public class Main {
    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            try {
                log.info("开始执行" + Thread.currentThread().getName());
                log.info("开始睡眠 5秒");
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                log.error(Thread.currentThread().getName() + "被中断了");
                e.printStackTrace();
            }
        }, "t1");
        thread.start();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        log.info(thread.currentThread().getName() + "状态:" + thread.getState().name());
        thread.interrupt();
    }
}



获得更好的可读性

package cn.meowrain;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;

@Slf4j
public class Main {
    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(() -> {
            try {
                log.info("开始执行" + Thread.currentThread().getName());
                log.info("开始睡眠 5秒");
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                log.error(Thread.currentThread().getName() + "被中断了");
                e.printStackTrace();
            }
        }, "t1");
        thread.start();
        TimeUnit.SECONDS.sleep(1);
        log.info(thread.currentThread().getName() + "状态:" + thread.getState().name());
        thread.interrupt();
    }
}