how to restart a thread

前端 未结 5 1581
梦毁少年i
梦毁少年i 2021-01-21 22:58

I tried to write a file monitor which will check the file if a new line is appended,the monitor in fact is a thread which will read the line by a randomaccessfile all the time.

5条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-21 23:22

    A thread in Java cannot be re-started. Every time you need to restart the thread you must make a new one.

    That said, you might want to look at:

    private void setRandomFile() {
            if (!monitoredFile.exists()) {
                log.warn("File [" + monitoredFile.getAbsolutePath()
                        + "] not exist,will try again after 30 seconds");
                try {
                    Thread.sleep(30 * 1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                setRandomFile();
                return;
            }
    // ....
    }
    

    Here you sleep for 30 seconds if the file does not exist, then recursively call the same function. Now, I don't know what business requirements you have, but if this recursion ran long enough you will run out of stack space. Perhaps you will be better served with a while loop or even better, a little synchronisation like a Semaphore.

提交回复
热议问题