开发者

Pass an actual command as argument Java

开发者 https://www.devze.com 2023-01-13 18:20 出处:网络
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

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.


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消