Java – use thread. Java in my main code currentThread. Is sleep () dangerous?
In my code I'm using
Thread.currentThread().sleep(sleepTime);
In the main (non thread object) part of the code
It seems to work normally, but I'm afraid there may be some hidden traps that will bite me in my ass in the future
Is there a better way to let your main process sit for a while? Or is this the prescribed method?
Edit:
Answer why I did this
I have a process that connects to a remote host through HTTP or FTP and performs operations
To put it another way
Something
Connect to remote
Make a remote connection
Close contact
More
Repeat if necessary
I found that in very rare cases, the connection will only enter La land It will not fail, it will not throw any exceptions, and it will disappear And it is blocked, so there is no inline way to set the timer
So, my solution is to do this
Something
Start new thread with connection
Use a timer in the main process (not in the generated thread) to enter an infinite loop and wait for any of them
a) The connection thread completes its task and sets some flags as complete
or
b) Wait for a preset period of time. If the connection thread does not report that it has completed, it will terminate and continue
In the main process, I plan to sleep for a while, wake up and look at max_ WAIT_ Whether the time has expired If not, please go back to bed and wait a minute
It seems to be more efficient than in a standard while loop (on the processor) because it interferes with the connection thread doing what it needs to do
I think my question is really... What's unsafe about this method I see from the answer that, given what I'm doing, it doesn't seem to be Maybe I should ask if there is a more standardized method?
Solution
There are no traps As long as you tell it, it will sleep
Your idea of applying to sleep for a long time may or may not have traps