Loading

代替Thread.sleep的平替方法

package cool.islj.thread;

import java.time.Duration;
import java.util.function.BooleanSupplier;

public class ThreadUtils {
    /**
     * 等待(supplier一开始为true则不等待)
     * @param period 检查周期,supplier一开始为false时的最低等待时间
     * @param timeOut 超时时间,最多等待时间
     * @param supplier 为true时不等待,否则等待其变为true或者超时
     * @return supplier为true返回true,否则返回false
     */
    public static boolean waitMillis(long period, long timeOut, BooleanSupplier supplier) {
        long waitTime = 0L;
        Duration duration = null;

        boolean result;
        do {
            long beginTime = System.currentTimeMillis();
            result = supplier != null && supplier.getAsBoolean();
            waitTime += System.currentTimeMillis() - beginTime;
            if (!result) {
                try {
                    Thread.yield();
                    if (duration == null) {
                        duration = Duration.ofMillis(timeOut);
                    }
                    synchronized (duration) {
                        duration.wait(period);
                    }
                    waitTime += period;
                } catch (InterruptedException ex) {
                    // 这里用log打印出来
                    ex.printStackTrace();
                }
            }
        } while (!result && waitTime < timeOut && !Thread.currentThread().isInterrupted());
        return result;
    }
}

posted @ 2024-02-29 10:09  星流残阳  阅读(219)  评论(0编辑  收藏  举报