是否可以 运行 在 Java RMI 的同一线程中远程调用两个不同的方法?
Is it possible to run remote calls to two different methods in the same thread in Java RMI?
假设 Remote class 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
。如果您需要 return 方法中的值,请将 Void
更改为适当的数据类型。
在 Java 8 中更简单,您不需要 Callable
s:
executor.submit(() -> {
// call the method you need here
});
假设 Remote class 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
。如果您需要 return 方法中的值,请将 Void
更改为适当的数据类型。
在 Java 8 中更简单,您不需要 Callable
s:
executor.submit(() -> {
// call the method you need here
});