[英]Java threads not sharing static data
我有兩個線程應該共享靜態變量數據(不是常量),它們必須相應地執行。 但是,除了每個線程保持其自己的靜態變量狀態之外,這些線程均無法獲取更新的靜態變量數據。
我將靜態變量放在一個單例中並聲明為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.
如果您打算改變其狀態,則聲明對單例揮發物的引用將無濟於事。 您需要使用由volatile變量引用的不可變單例,或者使該單例中的每個var都可變 。 這只是在您也沒有原子性問題的情況下。 第二種方法幾乎與完全沒有單例相同,只是沒有多個static volatile
全局變量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.