简体   繁体   English

有关Java中线程的说明

[英]Clarification regarding threads in Java

I am trying to figure some basic stuff in Java and needed help regarding Threads. 我试图弄清楚Java中的一些基本知识,并且需要有关线程的帮助。

Today I came across a piece of code in which new threads were being created in for loop as follows: 今天,我遇到了一段代码,其中在for循环中创建了新线程,如下所示:

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. 我假设t2.getId()和t2.getName()将打印相同的值,因为在循环的每次迭代中,新线程都被分配给同一对象线程对象T2。

However for every iteration a different value for getId and getName were printed. 但是,对于每次迭代,都会打印不同的getId和getName值。

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. 在这种情况下,如果在第一次迭代中为T2创建了线程局部变量,则在第二次迭代中将覆盖它们的值。

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. 我假设t2.getId()和t2.getName()将打印相同的值,因为在循环的每次迭代中,新线程都被分配给同一对象线程对象 T2。

No, a new Thread object is being assigned to the same reference varaible , t2. 不,将新的Thread 对象分配给同一参考变量 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. 变量,这里是t2,是指分配给它的任何对象,在这种情况下,变量名称是没有意义的,但是对象引用才是真正重要的。 Since you change the reference within the for loop, the object's "name" (if it has a name field) will likewise change. 由于您在for循环中更改了引用,因此对象的“名称”(如果它具有名称字段)将同样发生变化。

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. 我觉得完全理解这一关键区别是真正实现Java OOPS编程的核心,这是一旦实现的主要步骤之一,将极大地帮助程序员。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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