我想知道它是否可能以某种方式使用java 7或8
public class App{
public static void main(String[] args) {
new Thread(){
public void run(){
//Something
}
}.start().setName("Something") //Here!!
//Something
}
}
在您的示例中,由于start()
返回void
,因此无法实现。但是,取决于您调用的方法的实现。在一些设计中,我们设计(Builder pattern/ Fluent)
方法通常返回this
,在这种情况下,method chaining
是可能的。对于您的示例,您可以像下面这样做。
Thread t = new Thread() {
public void run() {
}
};
t.setName("Something");
t.start();
如果您只想在单个语句中声明,命名和启动线程,只需使用指定线程名称的构造函数:
new Thread("Something") { ... }.start();
不,这是不可能的,因为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()
只是为了有更多的电话