java 异步方法,如何在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.

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 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

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!");

Internally I'm using a class that implements Runnable and do some Reflection work to get the correct method object and invoking it.

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();

(At least in Java 8), you can use a lambda expression to shorten it to:

new Thread(() -> {

//Do whatever

}).start();

As simple as making a function in JS!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值