问题
In my application I am calling third part vendor web-service. I need to delay my thread processing to achieve required throughput supported by vendor webservice.
I have two options 1. Use Thread.Sleep 2. use ScheduledThreadPoolExecutor as mentioned in the post How to start a thread after specified time delay in java
Wanted to know which is better option as we are sending time critical information(Text Message) using Vendor webservice. Any help is appreciated.
回答1:
They're pretty much the same as ScheduledThreadPoolExecutor.scheduleWithFixedDelay
encapsulates the sleep call.
Since the delay is 100ms performance difference is kind of negligible. I'd go with ScheduledThreadPoolExecutor.scheduleWithFixedDelay
due to pooled threads. The amount of load put on the system would be manageable, you wouldn't have multiple threads waking up from sleep together to compete for resources.
Also from the doc
Thread pools address two different problems: they usually provide improved performance when executing large numbers of asynchronous tasks, due to reduced per-task invocation overhead, and they provide a means of bounding and managing the resources, including threads, consumed when executing a collection of tasks. Each ThreadPoolExecutor also maintains some basic statistics, such as the number of completed tasks.
回答2:
use the scheduler method, you can select fixed-rate or fixed-delay. look the source code:
/**
* Period in nanoseconds for repeating tasks. A positive
* value indicates fixed-rate execution. A negative value
* indicates fixed-delay execution. A value of 0 indicates a
* non-repeating task.
*/
private final long period;
来源:https://stackoverflow.com/questions/31882624/thread-delay-using-scheduler-or-thread-sleep