我一直在看着
Go’s goroutines最近,认为在Java有类似的东西会很好。就我已经搜索的常见方法并行化方法调用是做类似的:
final String x = "somethingelse";
new Thread(new Runnable() {
public void run() {
x.matches("something");
}
}).start();
这不是很优雅。有没有更好的方法这样做?我需要这样的解决方案在项目中,所以我决定实现我自己的包装类周围的异步方法调用。
我在J-Go发布了我的包装类。但我不知道它是否是一个很好的解决方案。用法很简单:
SampleClass obj = ...
FutureResult 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:
Go.with(obj).callLater("myRandomMethod");
//... Go away
if (Go.lastResult().isReady()) //Blocks until myRandomMethod has ended
System.out.println("Method is finished!");
在内部,我使用一个实现Runnable的类,并做一些反射工作,以获得正确的方法对象和调用它。
我想要一些关于我的小库和关于在Java中做这样的异步方法调用的意见。它是安全吗?是否已经有一个更简单的方法?