我不知道下面的事情是否可行。我想要一个 Runnable
的 run()
方法来包含 Runnable
本身,即
reconnects = 3;
Runnable executeAfter = () -> {
if ( --reconnects < 0 ) {
println("%nStop using port %d.", this.port);
//...
} else { // try to reconnect
println("%nReconnecting...");
cmdRun = new CmdRun(command, executeAfter);
(new Thread(cmdRun)).start();
//...
}
};
这样的事情有可能吗?如果是这样,如何? (CmdRun
的构造函数是 CmdRun(String command, Runnable executeAfter)
)
最佳答案
这里必须使用 lambda 吗?如果不是,切换到旧的等效语法应该很简单:
一个例子:
public class TestLambda {
static int count = 0;
public static void main(String[] args) {
// lambda not going to work
//Runnable foo = () -> { if (count < 5) { call(foo); } };
// nor
//Runnable foo = () -> { if (count < 5) { call(this); } };
// using old way of anonymous inner class will work
Runnable foo = new Runnable() {
@Override public void run() {
if (count < 5) {
call(this);
}
}
};
foo.run();
}
public static void call(Runnable action) {
count++;
System.out.println("in call " + count);
action.run();
}
}
关于java - 在 Java 中实现递归 lambda 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40624587/