java - 是否可以在 Java RMI 的同一线程中运行对两个不同方法的远程调用?

标签 java multithreading threadpool rmi

假设远程类RemoteServer有两个远程方法method1method2

是否可以在 Java RMI 中的服务器的同一线程中运行对这两个方法的远程调用?

已知method1将首先被调用。


我已阅读"Thread Usage in Remote Method Invocations" (below)并且没有任何想法。

A method dispatched by the RMI runtime to a remote object implementation may or may not execute in a separate thread. The RMI runtime makes no guarantees with respect to mapping remote object invocations to threads.

最佳答案

虽然你的问题表明你很有可能找到更好的程序设计,但如果你确实需要这样的功能,你可以通过单线程的ThreadPoolExecutor来实现它。只需将您的方法 method1()method2() 包装到两个不同的 Callable 中,并将它们提交到您的单线程池。

class Method1Task implements Callable<Void> {
    public Void call() throws Exception {
        // method 1 body here
        return null;
    }
}

class Method2Task implements Callable<Void> {
    public Void call() throws Exception {
        // method 2 body here
        return null;
    }
}

...

// Create a single-thread pool and use it to submit tasks
private final ExecutorService executor = Executors.newFixedThreadPool(1);

void method1() {
    executor.submit(new Method1Task());
}

void method2() {
    executor.submit(new Method2Task());
}

如果您需要等待方法完成,请使用 submit() 返回的 Future。如果您需要从方法返回值,请将 Void 更改为适当的数据类型。

在 Java 8 中更简单,您不需要 Callable:

executor.submit(() -> {
    // call the method you need here
});

关于java - 是否可以在 Java RMI 的同一线程中运行对两个不同方法的远程调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39100894/

相关文章:

java - 应用程序引擎上的可靠分布式缓存 (Java)

java - ANT 没有调用 JUnits

c# - C#在线程间安全使用LINQ

tomcat - netty , tomcat 线程模型

java - 带有 CXF 且不带注释的 WSDL2Java

java - 在使用以前的元素值对每个元素执行操作后,使用 Java 8 Stream Reduce 返回列表

c++ - 在线程中使用 std::string 函数安全吗? (c++)

java - 线程中的某些代码不重复

C#线程池限制线程

c# - 线程池死锁与 Task.Result