【问题标题】:Call methods from the same unique thread从同一个唯一线程调用方法
【发布时间】:2016-07-15 16:02:41
【问题描述】:

我有这样的服务,有很多方法:

public class MyService {
 public void method1(String arg0, int arg1) {...}
 public MyObject method2(Object arg0, String arg1, int arg2) {...}
 //...
}

到目前为止,MyService 的方法是从各种线程(Eclipse RCP 上下文)调用的。 我需要从同一个唯一线程调用该服务的所有方法。

我见过 SingleThreadExecutor,但我是否必须将每个方法定义为 Callable 并为每个方法创建一个类?另外,我不知道如何将各种参数传递给我的方法? 当然,对这些方法的所有调用都应该得到返回值(如果有的话)和现在的异常。

是否有一个简单的解决方案可以像这样转换所有调用:

myService.method1(arg0, arg1); 

到这样的事情:

executor.execute(myService.method1(arg0, arg1))

我会很感激一些例子。

【问题讨论】:

    标签: java multithreading methods parameters callable


    【解决方案1】:

    如果您使用 Java8 进行编译,则可以使用 lambda 表达式简化 execute 调用:

    executor.execute(() -> myService.method1(arg0, arg1));
    

    在 Java7 或更早版本中,您可以使用不太干净的匿名内部类:

    executor.execute(new Runnable() {
        @Override
        public void run() {
            myService.method1(arg0, arg1);
        }
    });
    

    无论哪种方式,您所做的都是提交一个实现Runnable 的对象,并使用一个调用相关方法的run() 方法。

    【讨论】:

    • 谢谢,这看起来像我想要的。最后我用 callable 做到了:Future result = (Future) myExecutor.submit(() -> { MyObject myObject; try { myObject = myService.method1(arg0, arg1); } catch (Exception e ) { LOG.error(); } return myObject; });结果.get();我现在遇到的问题,我不知道如何处理可调用之外的异常。你有什么想法吗?
    • @Zibus69,这应该是一个新问题,但是如果您向ExecutorService 提交Callable 而不是提交Runnable,您将得到一个Future 对象。您可以使用 future 来等待返回值或异常。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-27
    • 1970-01-01
    • 2013-07-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多