chathura
chathura

Reputation: 3452

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

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

Upvotes: 2

Views: 701

Answers (3)

adarshr
adarshr

Reputation: 62593

Thread t = new Thread("main") {
    {
        setName("DemoThread");
    } 
};

The above is an anonymous inner class being created. The {} is an instance initializer block in Java. It would be a static block if it had static { }.

Basically you can invoke any operations from the instance initializer block that belongs to the instance (this) reference.

In this case, it's calling setName on the current instance of Thread.

Upvotes: 2

JB Nizet
JB Nizet

Reputation: 691765

The code is creating an anonymous Thread subclass with

new Thread("main") {

};

In this anonymous class, there is an initialization block:

{setName("DemoThread");}

Upvotes: 1

Ted Hopp
Ted Hopp

Reputation: 234807

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.

Upvotes: 7

Related Questions