有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java线程中的数据成员会发生什么情况?

有人能解释一下线程执行时数据成员会发生什么情况吗?我的意思是,在下面的代码中,输出是我想要的,即线程名称及其对应的编号。但是,如果我将1线程的引用传递给所有其他线程,线程名称会有所不同,但所有线程名称都会打印数字50。为什么会这样

class Thread3 implements Runnable
{
int x;

    public void run()
    {
        for(int i=1;i<=5;i++)
        {
            System.out.println(Thread.currentThread().getName()+" "+ x);

            try{
                Thread.sleep(1000);
            }catch(Exception e){ }
        }   

    }
}
public class RunThread3 {

public static void main(String s[])
{
Thread3 t1=new Thread3();
t1.x=50;
Thread tt1=new Thread(t1,"thread1");
tt1.start();

Thread3 t2=new Thread3();
t2.x=100;
Thread tt2=new Thread(t2,"thread2");
tt2.start();

Thread3 t3=new Thread3();
t3.x=150;
Thread tt3=new Thread(t3,"thread3");
tt3.start();

for(int i=1;i<=5;i++)
        {
            System.out.println(Thread.currentThread().getName());
            try{
                Thread.sleep(1000);
            }catch(Exception e){ }
        }   

}
}

这里,一个线程的引用传递给所有其他线程

class Thread3 implements Runnable
{
int x;

    public void run()
    {
        for(int i=1;i<=5;i++)
        {
            System.out.println(Thread.currentThread().getName()+" "+ x);

            try{
                Thread.sleep(1000);
            }catch(Exception e){ }
        }   

    }
}
public class RunThread3 {

public static void main(String s[])
{
Thread3 t1=new Thread3();
t1.x=50;
Thread tt1=new Thread(t1,"thread1");
tt1.start();

Thread3 t2=new Thread3();
t2.x=100;
Thread tt2=new Thread(t1,"thread2");
tt2.start();

Thread3 t3=new Thread3();
t3.x=150;
Thread tt3=new Thread(t1,"thread3");
tt3.start();

for(int i=1;i<=5;i++)
        {
            System.out.println(Thread.currentThread().getName());
            try{
                Thread.sleep(1000);
            }catch(Exception e){ }
        }   

}
}

共 (2) 个答案

  1. # 1 楼答案

    这是你对java中线程和类的误解。 在代码中有两个不同的实体:java线程和自定义可运行类。 示例中得到的线程名称是java线程对象的名称。示例中得到的数字x是自定义可运行类的数字。请注意:我跳过了你们班的名字——这会造成误解。因此,如果您只使用一个自定义可运行对象,您将始终获得单个x

  2. # 2 楼答案

    在后面的代码中,您将线程t1的引用传递给所有:

    Thread3 t1=new Thread3();
    t1.x=50;
    Thread tt1=new Thread(t1,"thread1");
    tt1.start();
    Thread tt2=new Thread(t1,"thread2");
    tt2.start();
    Thread tt3=new Thread(t1,"thread3");
    tt3.start();
    

    这意味着所有线程的x值都将为50,当您执行代码时,您将获得预期值: thread1 50 thread2 50 main thread3 50 main thread1 50 thread3 50 thread2 50 thread1 50 main thread3 50 thread2 50 thread3 50 main thread2 50 thread1 50 main thread3 50 thread2 50 thread1 50

    在前一种情况下,你有不同的线程,它们相应地工作