Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import java.util.concurrent.atomic.AtomicBoolean;
import static com.google.common.base.Preconditions.checkNotNull;

public class Main {
    /**
     * sleep specified time.
     *
     * @param sleepTime sleep time in milliseconds
     * @return true if really sleep enough time, false if thread is interrupted
     */
    public static boolean sleep(long sleepTime) {
        try {
            Thread.sleep(sleepTime);
            return true;
        } catch (InterruptedException e) {
            return false;
        }
    }

    /**
     * sleep specified time with stop flag.
     * <p>
     * When flag turns to true, this method should immediately return.
     * </p>
     *
     * @param sleepTime sleep time in milliseconds
     * @param stopFlag  stop flag, if the value is true, end sleep
     * @return true if really sleep enough time, false if thread is interrupted
     */
    public static boolean sleep(long sleepTime, AtomicBoolean stopFlag) {
        checkNotNull(stopFlag);
        final long smallTime = 10;
        final long expectedEndTimestamp = System.currentTimeMillis() + sleepTime;

        while (true) {
            long leftTime = expectedEndTimestamp - System.currentTimeMillis();
            if (leftTime <= 0) {
                break;
            }
            if (stopFlag.get() || !sleep(getSmall(leftTime, smallTime))) {
                return false;
            }
        }
        return true;
    }

    private static long getSmall(long time1, long time2) {
        return time1 < time2 ? time1 : time2;
    }
}