I want to make a single thread which would contain 3 infinite tasks.
I want one task to run at a time and start/stop running task when required.
For example first I want task 1 to run, then I want task 2 to run but after stopping task 1 and again I want task 1 to run but after stopping of task 2 and so on.
Infinite task needs to check some condition and if that condition is satisfied perform some operations and if not satisfied sleep for few seconds and after wake up perform the above same operations again.
Infinite Runnable task looks some thing like this:
new Runnable(){
while(1){
if(TaskQueue.getInstance().size()<= 100){
TaskQueue.getInstance().push("add command to the end of queue");
}else{
try {
Thread.sleep(10000);
}catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Any help would be appreciated?
Edit : I modified my question. I want a continuous single running thread(some thing like looper ) to monitor 3 infinite tasks and control this single continuous running thread tasks from outside.
I finally made my task scheduler. The API of which looks something like this:
Runs one task at a time (because I used Executors.newSingleThreadExecutor()). We can control the execution of the task from outside:
Use this for start/stop thread in real-time:
For pause thread use this:
For resume thread use this:
For stop thread use this (Not recommended):
For currently stop thread use this:
You could also initialize a new thread, like:
After this you can start it at any point in your code by:
you can use Semaphore, to Manage the amount of signal.
The question is my first answer,thanks.
You must use a class like Thread that already implements Runnable.
And the way it works it's: