I'm currently using a separate thread in Java that could potentially be used for a lot of different functionality, and I'm wondering if there is a way to pass the command for an actual function call as a parameter. This would look something along the lines of:
class myWorkerThread implements Runnable
{
private (<String/whatever other type>) runCommand;
public myWorkerThread(<String/whatever other type> <my command>)
{
}
public void run()
{
//Actually run that command.
}
}
I'm hoping to get a tool that doesn't make me use an ugly switch case statement or something of the sort. The different functions I'd ask the thread to run have different parameters, but I'd like to be able to run them just with the same thread.
Follow up questions/links to other resources are great.
Thanks.
Normally, you'd do something like this by creating implementations of Runnable and running them with an Executor. The Executor manages your threads.
Using a Callable and a Future, you can also get results from tasks that you submit for asynchronous execution.
You cannot pass function pointers as parameters in Java. Optionally, you can define an interface supporting the operation and pass a reference to a an object implementing the interface. Call the needed method from that reference.
Also, your use of the word Command makes me think the Command Processor pattern might be of use.
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