如何使用Java 8将以下代码(特别是public void run()方法)转换为lambda?
Thread t1 = new Thread(new Runnable() -> {
for (int i = 0; i < 10; i++) {
System.out.println("Hello " + i);
try {
Thread.sleep(100);
}
catch (InterruptedException e) {
e.printStackTrace();
}
};
);
尝试:
"com.lmax" % "disruptor" % "3.3.5",
"org.apache.logging.log4j" % "log4j-api" % "2.8.2",
"org.apache.logging.log4j" % "log4j-core" % "2.8.2",
"org.apache.logging.log4j" %% "log4j-api-scala" % "2.8.2"
但Eclipse不断抛出错误......
答案 0 :(得分:8)
只需删除new Runnable
:
Thread t1 = new Thread(() -> { /* body */ });
您可能需要考虑将该主体拉出为“真实”方法,并改为使用方法引用:
static void doSomething() { /* body */ }
public static void main(String[] args) {
Thread t1 = new Thread(SampleApp::doSomething);
}
大lambda体不是特别易读。
答案 1 :(得分:0)
嗨,如果你想要内联你可以这样做
final Thread t1 = new Thread(()->{
for (int i = 0; i < 10; i++) {
System.out.println("Hello " + i);
try { Thread.sleep(100); }
catch (final InterruptedException e) {
e.printStackTrace();
}
}
});