简体   繁体   中英

Clarification regarding threads in Java

I am trying to figure some basic stuff in Java and needed help regarding Threads.

Today I came across a piece of code in which new threads were being created in for loop as follows:

public class TestThreads {
public static void main(String args[])
{
    Thread t1=new Thread();
    System.out.println("***************"+t1.getId());
    for(int i=0;i<5;i++)
    {
        Thread t2= new Thread();
        System.out.println("++++++++++++++++"+t2.getId());
        System.out.println("++++++++++++++++"+t2.getName());
    }
}

}

I was assuming that t2.getId() and t2.getName() will print the same values since in every iteration of the loop,the new thread is being assigned to same object thread object T2.

However for every iteration a different value for getId and getName were printed.

Can someone explain how that is possible, aren't we assigning the new thread to same object.

In that case if there were any thread local variables for T2 were created in first iteration ,in the second iteration will their values be overridden.

This may sound a silly question but please help me out.

You're confusing object with reference variable .

I was assuming that t2.getId() and t2.getName() will print the same values since in every iteration of the loop,the new thread is being assigned to same object thread object T2.

No, a new Thread object is being assigned to the same reference varaible , t2.

The variable, here t2, refers to whatever object is assigned to it, and the variable name is meaningless in this context, but rather the object reference is what really matters. Since you change the reference within the for loop, the object's "name" (if it has a name field) will likewise change.

I feel that fully understanding this key distinction, one that really gets to the core of Java OOPS programming, is one of those major steps that once achieved will help the programmer greatly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM