gpt4 book ai didi

java - 在构造函数中设置 ThreadLocal 变量是否有效?

转载 作者:行者123 更新时间:2023-11-30 08:17:18 25 4
gpt4 key购买 nike

我正在学习 java 线程,我参加了有关本地线程值的类(class),我决定制作一个使用它们的程序。我在构造函数(线程构造函数)中设置本地线程值,将其显示在屏幕上以检查它是否有效,但是当我启动线程时,本地值变为 NULL,因此我得到 NullPointerException。我是否错过了什么,或者我只能在启动方法中设置本地线程值?

package practice;
import static java.lang.System.out;
import java.util.Scanner;
class Try
{
Thread a1,a2,a3;
int x=0;
synchronized void change(int who){
out.println("who called"+who);
out.println("x initial="+x);
x++;
out.println("x after="+x);
}
class now implements Runnable{
ThreadLocal<Integer> id=new ThreadLocal<Integer>();
public void run(){
for(int i=1;i<=25;i++){
out.println("im running id="+id.get());
change(id.get());
out.println("after call me="+id.get());
}
}
now(int givenid){
out.println("my givenid is "+givenid);
id.set(givenid);
out.println("my id is "+id.get());
}
}
public static void main(String[] args)
{
new Try();
}


Try(){

a1=new Thread(new now(1));
a2=new Thread(new now(2));
a1.start();
a2.start();
}

}

最佳答案

我真的很喜欢类塔尔的答案,但我只是想通过添加一些打印来说明你的代码会发生什么......

package threads;

import static java.lang.System.out;

class Main {
Thread a1, a2, a3;
int x = 0;

public Main() {
out.println("Current thread (in Main's constructor): " + Thread.currentThread().getName());
a1 = new Thread(new MyRunnable(1));
a2 = new Thread(new MyRunnable(2));
a1.start();
a2.start();
}

private synchronized void change(int who) {
out.println("Current thread (in change() method): " + Thread.currentThread().getName());
out.println("who called" + who);
out.println("x initial=" + x);
x++;
out.println("x after=" + x);
}

private class MyRunnable implements Runnable {
ThreadLocal<Integer> id = new ThreadLocal<Integer>();

public MyRunnable(int givenid) {
out.println("Current thread (in MyRunnable's constructor): " + Thread.currentThread().getName());
out.println("my givenid is " + givenid);
id.set(givenid);
out.println("my id is " + id.get());
}

public void run() {
out.println("Current thread (in run() method): " + Thread.currentThread().getName());
out.println("im running id=" + id.get());
change(id.get());
out.println("after call me=" + id.get());
}
}

public static void main(String[] args) {
new Main();
}
}

输出是:

Current thread (in Main's constructor): main
Current thread (in MyRunnable's constructor): main
my givenid is 1
my id is 1
Current thread (in MyRunnable's constructor): main
my givenid is 2
my id is 2
Current thread (in run() method): Thread-0
Current thread (in run() method): Thread-1
im running id=null
im running id=null

抱歉稍微更改了名称。

正如您所见,在实例化 MyRunnable (您的 now 类)时,您在 ma​​in 中设置了 ThreadLocal线。这就是为什么您无法通过其他线程访问它。

关于java - 在构造函数中设置 ThreadLocal 变量是否有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29471004/

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