将实际命令作为参数传递 Java

发布于 2024-09-17 07:24:50 字数 502 浏览 5 评论 0原文

我目前在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

染年凉城似染瑾 2024-09-24 07:24:50

通常,您可以通过创建 的实现来执行类似的操作可运行使用 Executor 运行它们。 Executor 管理您的线程。

使用 Callable< /a> 和 Future,您还可以从您 提交 进行异步执行。

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.

错爱 2024-09-24 07:24:50

在 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.

聆听风音 2024-09-24 07:24:50

您可以使用 execute() 方法创建一个 Command 接口。
每个命令将是一个实现该接口的单独类。

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

源来凯始玺欢你 2024-09-24 07:24:50

您可能还想看看 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文