Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setting the thread's name when Thread object is created?

Tags:

java

I'm new to Java. Can anyone explain what happens in the main method??

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());
    }
}
like image 448
chathura Avatar asked Nov 28 '25 17:11

chathura


1 Answers

This line:

{setName("DemoThread");}

is called an initializer block (or instance initializer block). It looks like a static initializer block, but without the static keyword. It's useful for anonymous classes because they can't have named constructors. More details can be found here.

like image 112
Ted Hopp Avatar answered Nov 30 '25 07:11

Ted Hopp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!