Java多线程和全局变量

lul*_*u88 9 java multithreading thread-safety

我有一个Java类,它启动了2个独立的线程.第一个线程启动正常,所有变量都正确.

当我启动第二个线程时,来自线程1的全局变量更改为线程2中设置的值.

我已经尝试添加全局变量更新的同步块,但这不起作用.

有没有办法解决这个问题?我希望每个线程都启动并使用自己的值而不会干扰其他线程值.

编辑:

我的Thread类的片段:

  public abstract class ConsumerIF implements Runnable {

      public static Element root = null;
      public static String name = null;
      public static String type = null;
      public static String location = null;

      public final synchronized void reconfigure() throws FatalDistributionException {


            Document doc = builder.build(new StringReader(xmlCollector));
            root = doc.getRootElement();
            Element nameElement = root.getChild("name");
            Element typeElement = root.getChild("type");
            Element locationElement = root.getChild("location");
            Element scheduleElement = root.getChild("schedule");

            if (nameElement != null && typeElement != null && locationElement != null){
                name = nameElement.getTextTrim();
                type = typeElement.getTextTrim();
                location = locationElement.getTextTrim();
            }

      }
  }
Run Code Online (Sandbox Code Playgroud)

kol*_*aTM 13

静态变量在所有线程之间共享,这就是使它们成为静态的.如果要使用不同的值,请使用ThreadLocals或(更好),在不同的线程中使用具有非静态变量的不同对象.没有进一步的代码,很难说更多.


Bri*_*new 6

同步仅控制线程对共享状态的访问.

如果你想要每个线程单独的状态,那么你需要为每个线程声明该信息的不同实例(例如类).例如简单地实例在每一个新的对象Threadrun()方法,或执行所讨论的结构的副本(例如,集合的深层副本)

另一种方法是调查ThreadLocal,其中每个Thread将具有指定资源的不同副本.