how to restart a thread

前端 未结 5 1553
梦毁少年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条回答
  •  萌比男神i
    2021-01-21 23:36

    You don't restart a Thread, instead you create a new one each time you want to start a thread.

    A better alternative may be to use Executors.newCachedThreadPool() which gives you a pool of thread which will be started/recycle for you.

    BTW: You are using recursion rather than a loop to poll if the file exists. Using recursion can mean if you wait too long it will throw a StackOverflowError. IMHO you shouldn't wait at all, the polling thread should repeatedly attempt to open the file until it is told to stop (or the file appears)

    Your current implementation also means if the file is replaced, you will have to reopen the file in the background thread anyway.

提交回复
热议问题