Java: set timeout on a certain block of code?

前端 未结 11 1005
终归单人心
终归单人心 2020-11-27 03:45

Is it possible to force Java to throw an Exception after some block of code runs longer than acceptable?

11条回答
  •  难免孤独
    2020-11-27 04:10

    Instead of having the task in the new thread and the timer in the main thread, have the timer in the new thread and the task in the main thread:

    public static class TimeOut implements Runnable{
        public void run() {
            Thread.sleep(10000);
            if(taskComplete ==false) {
                System.out.println("Timed Out");
                return;
            }
            else {
                return;
            }
        }
    }
    public static boolean taskComplete = false;
    public static void main(String[] args) {
        TimeOut timeOut = new TimeOut();
        Thread timeOutThread = new Thread(timeOut);
        timeOutThread.start();
        //task starts here
        //task completed
        taskComplete =true;
        while(true) {//do all other stuff }
    }
    

提交回复
热议问题