Java中的时间限制后如何停止方法?

时间:2019-06-19 11:55:55

标签: java multithreading time-limiting

我想对方法设置时间限制,如果超出限制,则打印失败消息并关闭该方法。 我该怎么办?

1 个答案:

答案 0 :(得分:1)

尝试以下代码:

这里,当您的超时时间到期时,您可以将正在运行的成员变量设置为false,以确保工作人员将退出while循环

import java.util.concurrent.TimeUnit;

public class Worker implements Runnable {
    private boolean running;

    public Worker() {
        this.running = true;
    }

    @Override
    public void run() {
        while (this.running) {
            // Long Task
        }
    }

    /**
     * Sets the running.
     *
     * @param running the new running
     */
    public void setRunning(boolean running) {
        this.running = running;
    }

    public static void main(String[] args) {
        int timeOutInMin = 5;
        Worker worker = new Worker();
        new Thread(worker).start();
        try {
            TimeUnit.MINUTES.sleep(timeOutInMin);
            worker.setRunning(false);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}