如何异步调用Java中的方法 [英] How to asynchronously call a method in Java

查看:46
本文介绍了如何异步调用Java中的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近一直在查看 Go 的 goroutines 并认为它会很好在 Java 中有类似的东西.据我搜索,并行化方法调用的常用方法是执行以下操作:

I've been looking at Go's goroutines lately and thought it would be nice to have something similar in Java. As far as I've searched the common way to parallelize a method call is to do something like:

final String x = "somethingelse";
new Thread(new Runnable() {
           public void run() {
                x.matches("something");             
    }
}).start();

那不是很优雅.有更好的方法吗?我在一个项目中需要这样的解决方案,所以我决定围绕异步方法调用实现我自己的包装类.

Thats not very elegant. Is there a better way of doing this? I needed such a solution in a project so I decided to implement my own wrapper class around a async method call.

我在 J-Go 中发布了我的包装类.但我不知道这是否是一个好的解决方案.用法很简单:

I published my wrapper class in J-Go. But I don't know if it is a good solution. The usage is simple:

SampleClass obj = ...
FutureResult<Integer> res = ...
Go go = new Go(obj);
go.callLater(res, "intReturningMethod", 10);         //10 is a Integer method parameter
//... Do something else
//...
System.out.println("Result: "+res.get());           //Blocks until intReturningMethod returns

或不那么冗长:

Go.with(obj).callLater("myRandomMethod");
//... Go away
if (Go.lastResult().isReady())                //Blocks until myRandomMethod has ended
    System.out.println("Method is finished!");

在内部,我正在使用一个实现 Runnable 的类并做一些反射工作来获取正确的方法对象并调用它.

Internally I'm using a class that implements Runnable and do some Reflection work to get the correct method object and invoking it.

我想对我的小库以及在 Java 中进行像这样的异步方法调用的主题发表一些意见.安全吗?已经有更简单的方法了吗?

I want some opinion about my tiny library and on the subject of making async method calls like this in Java. Is it safe? Is there already a simplier way?

推荐答案

我刚刚发现有一种更简洁的方式来完成您的工作

I just discovered that there is a cleaner way to do your

new Thread(new Runnable() {
    public void run() {
        //Do whatever
    }
}).start();

(至少在 Java 8 中),您可以使用 lambda 表达式将其缩短为:

(At least in Java 8), you can use a lambda expression to shorten it to:

new Thread(() -> {
    //Do whatever
}).start();

就像在 JS 中创建一个函数一样简单!

As simple as making a function in JS!

这篇关于如何异步调用Java中的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆