gpt4 book ai didi

java - 创建 Thread 对象时设置线程的名称?

转载 作者:行者123 更新时间:2023-12-03 03:20:48 24 4
gpt4 key购买 nike

我是 Java 新手。谁能解释一下 main 方法中发生了什么?

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");}

称为初始化 block (或实例初始化 block )。它看起来像一个静态初始化 block ,但没有 static 关键字。它对于匿名类很有用,因为它们不能具有命名构造函数。更多详情可查看here .

关于java - 创建 Thread 对象时设置线程的名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8892072/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com