Reputation: 33
My goal is to have a Queue of method calls contained in a class that extends Thread whose run method pops a method call off of the queue once every 15 seconds. This could be done in a shady way using Strings, ints, or chars in a mammoth switch case, but I was wondering if anyone else has a far more elegant solution to this issue.
Something that would look like this?
public class Potato extends Thread{
Queue<Methods> methodsQueue = new LinkedList<Methods>();
public Potato(){}
run(){
methodsQueue.poll();//This would execute a method
}
//Methods of this class...
}
Upvotes: 3
Views: 1449
Reputation: 33
This one liner (which is available in the Android API) gives you the same functionality you're trying to implement:
ScheduledExecutorService s = Executors.newScheduledThreadpool(numThreads);
If you need to run arbitrary methods using reflection, then submitting them to this service is as easy as wrapping each one in custom Runnable argument and calling s.schedule(Runnable,long,TimeUnit);
I can't think of a more elegant, less cumbersome solution to your problem (at least when using Java). And it comes with the benefit of having been tested and used as part of the core Java API since 2004. – @CodeBlind
Upvotes: 0
Reputation: 12953
You can use an interface to wrap the methods you want to call:
public interface MethodWrapper {
void execute();
}
public class Potato extends Thread{
Queue<MethodWrapper> methodsQueue = new LinkedList<>();
public Potato(){}
run(){
methodsQueue.poll().execute();
}
//Methods of this class...
}
Upvotes: 3