我一直在看 Go的够程最近并认为这将是很好有类似的东西在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-去出版了我的包装类。但我不知道这是否是一个很好的解决方案。用法很简单:
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中的问题的一些意见。是否安全?有没有已经是simplier方式?
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前pression把它缩短:
(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中的方法
发布评论