I have a problem to solve. in which i need to run list of runnable objects with some delay in each request execution.
Say for ex I have a list like below
List<MyReqObject> myReqObjects=new ArrayList<MyReqObject>();
and I have created an executor with X number of threads like below
ExecutorService execute=Executors.newFixedThreadPool(X)
now using execute.invokeAl(myReqObjects);
i an trying to invoke all these requests...
but I should have a delay in between these. to achieve this I tried
ScheduledExecutorService scheduler =Executors.newScheduledThreadPool(1);
scheduler.scheduleAtFixedRate(myObject, 2, 7, SECONDS);
but here I cannot send list as a argument so I can execute same request for 7 sec with delay of 2 sec...
so is there a way to solve my problem please suggest me
In the nomenclature of most operating systems, "running" means that the thread actually is executing instructions on some CPU, and "runnable" means that nothing prevents the thread from "running" except the availability of a CPU to run on. A Java program can not tell the difference between those two states.
ThreadPoolExecutor is an ExecutorService to execute each submitted task using one of possibly several pooled threads, normally configured using Executors factory methods. It also provides various utility methods to check current threads statistics and control them.
Runnable is an interface which represents a task that could be executed by either a Thread or Executor or some similar means. On the other hand, Thread is a class which creates a new thread. Implementing the Runnable interface doesn't create a new thread. Java Docs clearly explains the difference between them.
The executor service creates and maintains a reusable pool of threads for executing submitted tasks. The service also manages a queue, which is used when there are more tasks than the number of threads in the pool and there is a need to queue up tasks until there is a free thread available to execute the task.
create a Timer:
Timer timer = new Timer();
if you need to run it once then:
timer.schedule(new TimerTask() {
@Override
public void run() {
// Your code here
}
}, 2*1000);
to run repeatedly:
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
// Your code here
}
}, 2*1000);
see some coding examples for Timer and TimerTask here
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