我一直在看 Go's goroutines最近并认为在 Java 中有类似的东西会很好。据我搜索,并行化方法调用的常用方法是执行以下操作:
final String x = "somethingelse";
new Thread(new Runnable() {
public void run() {
x.matches("something");
}
}).start();
那不是很优雅。 有更好的方法吗?我在一个项目中需要这样的解决方案,所以我决定围绕异步方法调用实现我自己的包装类。
我在 J-Go 中发布了我的包装类.但我不知道这是否是一个好的解决方案。用法很简单:
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 的类并做一些反射工作来获取正确的方法对象并调用它。
我想对我的小型库以及在 Java 中进行这样的异步方法调用的主题提出一些意见。安全吗?有没有更简单的方法?
最佳答案
我刚刚发现有一种更清洁的方法来做你的
new Thread(new Runnable() {
public void run() {
//Do whatever
}
}).start();
(至少在 Java 8 中),您可以使用 lambda 表达式将其缩短为:
new Thread(() -> {
//Do whatever
}).start();
就像在 JS 中做一个函数一样简单!
关于java - Java中如何异步调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1842734/