假设远程类RemoteServer
有两个远程方法method1
和method2
。
是否可以在 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/