Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java threads : ExecutorService delay between threads

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?

like image 505
yapkm01 Avatar asked Jan 06 '12 15:01

yapkm01


People also ask

Is ExecutorService submit asynchronous?

The Java ExecutorService interface, java. util. concurrent. ExecutorService , represents an asynchronous execution mechanism which is capable of executing tasks concurrently in the background.

What is ExecutorService in multithreading in Java?

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.

What are the advantages of using ExecutorService instead of creating threads directly?

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.


1 Answers

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);
like image 162
Peter Lawrey Avatar answered Sep 28 '22 05:09

Peter Lawrey