将实际命令作为参数传递 Java
我目前在 Java 中使用一个单独的线程,它可能用于许多不同的功能,我想知道是否有一种方法可以将实际函数调用的命令作为参数传递。这看起来大概是这样的:
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.
}
}
我希望得到一个工具,不会让我使用丑陋的 switch case 语句或类似的东西。我要求线程运行的不同函数具有不同的参数,但我希望能够使用同一线程运行它们。
跟进问题/其他资源的链接非常棒。
谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
通常,您可以通过创建 的实现来执行类似的操作
可运行
和使用Executor
运行它们。Executor
管理您的线程。使用
Callable
< /a> 和Future,
您还可以从您 提交 进行异步执行。
Normally, you'd do something like this by creating implementations of
Runnable
and running them with anExecutor
. TheExecutor
manages your threads.Using a
Callable
and aFuture
, you can also get results from tasks that you submit for asynchronous execution.在 Java 中不能将函数指针作为参数传递。或者,您可以定义支持该操作的接口并将引用传递给实现该接口的对象。从该引用中调用所需的方法。
另外,您使用“命令”一词让我想到 命令处理器模式可能有用。
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.
您可以使用
execute()
方法创建一个Command
接口。每个命令将是一个实现该接口的单独类。
You can make a
Command
interface with anexecute()
method.Each command would then be a separate class implementing the interface.
您可能还想看看 Java Reflection。
这是因为您可以使用字符串对象按名称调用方法。
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.