Java 设置螺纹';创建线程对象时的名称?
我是Java新手。有人能解释一下主方法中发生了什么吗Java 设置螺纹';创建线程对象时的名称?,java,Java,我是Java新手。有人能解释一下主方法中发生了什么吗 class Demo { public static void main(String []args) { //setting a name using the constructor Thread t=new Thread("main"){ //what is this? a static block?? need an explanation to this.
class Demo {
public static void main(String []args) {
//setting a name using the constructor
Thread t=new Thread("main"){
//what is this? a static block?? need an explanation to this.
{setName("DemoThread");}
};
//output is DemoThread. Since it set the name again.
System.out.println(t.getName());
}
}
这一行:
{setName("DemoThread");}
{setName("DemoThread");}
称为初始值设定项块(或实例初始值设定项块)。它看起来像一个静态初始值设定项块,但没有
static
关键字。它对于匿名类很有用,因为它们不能有命名构造函数。可以找到更多详细信息。代码正在使用创建匿名线程子类
new Thread("main") {
};
在此匿名类中,有一个初始化块:
上面是一个正在创建的匿名内部类。{}
是Java中的实例初始值设定项块。如果它有static{}
,它将是一个静态块
基本上,您可以从属于实例(this
)引用的实例初始值设定项块调用任何操作
在本例中,它在线程的当前实例上调用setName
Thread t = new Thread("main") {
{
setName("DemoThread");
}
};