我想知道这是否可能以某种方式请java 7或8
public class App{
public static void main(String[] args) {
new Thread(){
public void run(){
//Something
}
}.start().setName("Something") //Here!!
//Something
}
}
最佳答案
不,这是不可能的,因为 start()
和 setName()
都不返回线程。创建的匿名类是Thread
的子类,因此可以赋值给这样一个变量:
Thread thread = new Thread {
// something
};
thread.setName(...);
thread.setPriority(...);
thread.start();
或使用函数符号:
Thread thread = new Thread( () -> { ... } );
thread.setName(...);
thread.setPriority(...);
thread.start();
和我的首选(没有创建额外的类),使用方法引用:
Thread thread = new Thread(this::runInThread);
thread.setName(...);
thread.setPriority(...);
thread.start();
...
}
private void runInThread() {
// something to run in thread
}
添加了setPriority()
只是为了有更多的调用
关于java - 是否可以从匿名类调用多个方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55774591/