gpt4 book ai didi

java - 多线程程序输出不符合预期

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:15:54 25 4
gpt4 key购买 nike

我写了一个小程序,我在类级别字段中存储线程名称并打印它。

public class ThreadClass implements Runnable {

private String threadName = null;

@Override
public void run() {
System.out.println(" thread name " + threadName);
System.out.println(" current thread >>>>>> "
+ Thread.currentThread().getName());
threadName = Thread.currentThread().getName();
}
}

我编写了一个测试类,其中我创建了 10 个线程并启动了它们。

public class ThreadController {
public static void main(String[] args) {
ThreadClass threadClass = new ThreadClass();
Thread t1 = new Thread(threadClass, "T1");
Thread t2 = new Thread(threadClass, "T2");
Thread t3 = new Thread(threadClass, "T3");
Thread t4 = new Thread(threadClass, "T4");
Thread t5 = new Thread(threadClass, "T5");
Thread t6 = new Thread(threadClass, "T6");
Thread t7 = new Thread(threadClass, "T7");
Thread t8 = new Thread(threadClass, "T8");
Thread t9 = new Thread(threadClass, "T9");
Thread t10 = new Thread(threadClass, "T10");

t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
t6.start();
t7.start();
t8.start();
t9.start();
t10.start();
}
}

我得到以下输出。

 thread name null
thread name null
thread name null
current thread >>>>>> T1
current thread >>>>>> T6
current thread >>>>>> T2
thread name T2
thread name T2
thread name null
thread name null
thread name null
current thread >>>>>> T4
current thread >>>>>> T7
current thread >>>>>> T8
current thread >>>>>> T9
thread name T1
current thread >>>>>> T5
thread name T1
current thread >>>>>> T3
current thread >>>>>> T10

我的疑问是,如果每个线程都创建字段变量的本地副本,那么为什么我并不总是将线程名称设置为 null。抱歉,这听起来像是一个愚蠢的问题,但我正在尝试学习线程。

最佳答案

线程将不会创建其访问的字段的本地副本。在您的实现中,所有线程都试图访问实例 threadClass 中的相同字段,这就是为什么它不总是 null 的原因。

如下更改您的来源,您将获得预期的行为。

Thread t1 = new Thread(new ThreadClass(), "T1");
Thread t2 = new Thread(new ThreadClass(), "T2");
Thread t3 = new Thread(new ThreadClass(), "T3");
Thread t4 = new Thread(new ThreadClass(), "T4");
Thread t5 = new Thread(new ThreadClass(), "T5");
Thread t6 = new Thread(new ThreadClass(), "T6");
Thread t7 = new Thread(new ThreadClass(), "T7");
Thread t8 = new Thread(new ThreadClass(), "T8");
Thread t9 = new Thread(new ThreadClass(), "T9");
Thread t10 = new Thread(new ThreadClass(), "T10");

关于java - 多线程程序输出不符合预期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20624058/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com