如何在Java中异步调用方法

编程入门 行业动态 更新时间:2024-10-23 23:31:36
本文介绍了如何在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

或更少verbose:

or less verbose:

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

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

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中异步调用方法

本文发布于:2023-11-11 10:41:55,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1578193.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:方法   如何在   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!