views:

75

answers:

4

Hello,

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.

+4  A: 

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.

Mike
To supplement, the interface can be implemented and passed inline to the method as an anonymous class. You need the interface because you need to know how to call it from your worker thread.
Peter DeWeese
+1  A: 

You can make a Command interface with an execute() method.
Each command would then be a separate class implementing the interface.

SLaks
+4  A: 

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.

erickson
A: 

You might also want to have a look a Java Reflection.

This would be because you can be Invoking Methods by Name with the use of a string object.

mikek3332002
Yuck, only use reflection if there is no other option
Ishtar
Well yeah, it is a bit like `goto` where it should be used only in an specific cases.
mikek3332002