Java线程不共享静态数据

时间:2012-07-16 11:25:48

标签: java multithreading sharing static-members

我有两个线程,它们应该共享静态变量数据(不是常量),它们必须相应地执行。但是这些线程中没有一个能够获得更新的静态变量数据,除了每个线程都保持静态变量的自身状态。

我已将静态变量放在单例中并将其声明为volatile,结果仍然相同。

有人可以用这种方法提出问题,以及如何解决这个问题。

THX, AJ

below is the code

following is the singleton class

***************************************************************************
public class ThreadFinder {

    public static String pageName;//HashMap threadInfo = new HashMap(); //new HashMap();

private static ThreadFinder singletonObject;
/** A private Constructor prevents any other class from instantiating. */
private ThreadFinder () {
    }
public static synchronized ThreadFinder getSingletonObject() {
    if (singletonObject == null) {
        singletonObject = new ThreadFinder();
    }
    return singletonObject;
}
public static synchronized void setPageName(String Name) {

    pageName = Name;
    //return;
}
public static synchronized String getPageName() {

    return pageName;
    //return;
}
public Object clone() throws CloneNotSupportedException {
    throw new CloneNotSupportedException();
}
//public static void main(String args[])
//{
    //ThreadFinder.getSingletonObject().setPageName("IDEN");
    //System.out.println("page name--------->"+ThreadFinder.getSingletonObject().getPageName());
    //ThreadFinder.getSingletonObject().setPageName("THER");
    //System.out.println("page name--------->"+ThreadFinder.getSingletonObject().getPageName());
//}
}

********************************************************************************

from page 1 below code executes and sets the singleton page variable value to "A" and first pollertimer thread uses the page value as A.

m_poller.setModbusMaster(this.m_connection.getModbusMaster());
m_poller.addListener(this);
ThreadFinder.getSingletonObject().setPageName("A");  //Setting the page name here
PollerTimer polerTimerThread = new PollerTimer(period,"A");  // this is thread

*********************************************************************************

from page2 below code executes and sets the singleton page variable value to "B" and second pollertimer thread uses the page value as B.

m_poller.setModbusMaster(this.m_connection.getModbusMaster());
m_poller.addListener(this);
ThreadFinder.getSingletonObject().setPageName("B");  //Setting the page name here
PollerTimer polerTimerThread = new PollerTimer(period,"B");  // this is thread

***********************************************************************************

Now when first pollertimer thread queries page value using getPageName() it is getting value A instead of B, though it was updated to B by the second thread.

1 个答案:

答案 0 :(得分:3)

如果您打算改变其状态,声明对单例 volatile的引用将无济于事。您需要使用由volatile var引用的不可变单例,或者在该单例volatile中使每个单独的var 。这只是在你没有原子性问题的情况下。第二种方法几乎与没有单身的方法相同,只是一些static volatile全局变量。