gpt4 book ai didi

java - 为每个线程获取该程序的输出 null

转载 作者:行者123 更新时间:2023-11-30 06:45:38 25 4
gpt4 key购买 nike

我的输出:-客户线程 - 1....使用客户 ID 执行:null客户线程 - 4....使用客户 ID 执行:null客户线程 - 3....使用客户 ID 执行:null客户线程 - 2....使用客户 ID 执行:null

请解释为什么在每种情况下都为 null。为什么值不递增在此处输入代码

封装测试;

class CustomerThread extends Thread {
static Integer custId = 0;

private static ThreadLocal tl = new ThreadLocal() {
protected Integer intialValue() {
return ++custId; //This ++custId is not incrementing
}
};

CustomerThread(String name) {
super(name);
}

public void run() {
System.out.println(Thread.currentThread().getName() + "....executing with customer id :" + tl.get());?// tl.get() is not getting the values
}
}

class Test {
public static void main(String[] args) {
CustomerThread c1 = new CustomerThread("Customer Thread - 1");
CustomerThread c2 = new CustomerThread("Customer Thread - 2");
CustomerThread c3 = new CustomerThread("Customer Thread - 3");
CustomerThread c4 = new CustomerThread("Customer Thread - 4");
c1.start();
c2.start();
c3.start();
c4.start();
}
}

最佳答案

您实际上需要 set() 和 get() 来与 ThreadLocal 变量交互:

class CustomerThread extends Thread {
private static int customerID = 0;

private static ThreadLocal tl = new ThreadLocal<Integer>() {
@Override
protected Integer initialValue() {
return ++customerID;
}
};

CustomerThread(String name) {
super(name);
}

public void run() {
tl.set(tl.get());
System.out.println(Thread.currentThread().getName() + "....executing with customer id :" + tl.get());
}
}

输出:

Customer Thread - 1....executing with customer id :1
Customer Thread - 3....executing with customer id :3
Customer Thread - 4....executing with customer id :4
Customer Thread - 2....executing with customer id :2

关于java - 为每个线程获取该程序的输出 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43724337/

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