简体   繁体   English

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

[英]Is it possible to run remote calls to two different methods in the same thread in Java RMI?

Suppose that Remote class RemoteServer has two remote methods method1 and method2 . 假设Remote class RemoteServer具有两个远程方法method1method2

Is it possible to run the remote calls to these two methods in the same thread of the server in Java RMI? 是否可以在Java RMI的服务器的同一线程中运行对这两个方法的远程调用?

It is known that method1 will be called first. 已知将首先调用method1


I have read "Thread Usage in Remote Method Invocations" (below) and have no ideas. 我已经阅读了“远程方法调用中的线程使用情况”(如下) ,并且没有任何想法。

A method dispatched by the RMI runtime to a remote object implementation may or may not execute in a separate thread. RMI运行时调度到远程对象实现的方法可能会或可能不会在单独的线程中执行。 The RMI runtime makes no guarantees with respect to mapping remote object invocations to threads. RMI运行时不保证将远程对象调用映射到线程。

Though your question indicates that there's a good chance you can find better program design, if you really need such functionality, you can implement it by means of ThreadPoolExecutor with a single thread. 尽管您的问题表明您很有可能找到更好的程序设计,但是如果您确实需要这种功能,则可以使用ThreadPoolExecutor通过单个线程来实现。 Just wrap your methods method1() and method2() into two different Callable 's and submit them to your single-threaded pool. 只需将方法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());
}

If you need to wait for method completions, use Future s that are returned by submit() s. 如果需要等待方法完成,请使用Future submit()返回的Future If you need to return values from the methods, change Void for appropriate data types. 如果您需要从方法中返回值,则将Void更改为适当的数据类型。

In Java 8 it's simpler, you don't need the Callable s: 在Java 8中,它更简单,您不需要Callable

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM