I know the traditional way to delay a thread by using sleep method. My question is supposedly i have the following:
ExecutorService threadExecutor = Executors.newFixedThreadPool(5);
Is there a way say by using ExecutorService class to have a delay between each threads without using sleep method? I mean is there a method in ExecutorService class for this purpose?
The Java ExecutorService interface, java. util. concurrent. ExecutorService , represents an asynchronous execution mechanism which is capable of executing tasks concurrently in the background.
ExecutorService is a JDK API that simplifies running tasks in asynchronous mode. Generally speaking, ExecutorService automatically provides a pool of threads and an API for assigning tasks to it.
Below are some benefits: Executor service manage thread in asynchronous way. Use Future callable to get the return result after thread completion. Manage allocation of work to free thread and resale completed work from thread for assigning new work automatically.
Do you mean something like
ScheduledExecutorService service = Executors.newScheduledThreadPool(5);
service.scheduleAtFixedRate(task, initialDelay, period, TimeUnit.MILLISECONDS);
If you want three tasks, 10 seconds apart you can do
service.execute(task1);
service.schedule(task2, 10, TimeUnit.SECONDS);
service.schedule(task3, 20, TimeUnit.SECONDS);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With