我最近一直在研究Go语言中的协程(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中进行此类异步方法调用的意见。这样做是否安全?是否已经有更简单的方法了?