我有兩個線程應該共享靜態變量數據(不是常量),他們必須相應地執行。但是這些線程中沒有一個能夠獲得更新的靜態變量數據,除了每個維護靜態變量的狀態之外。Java線程不共享靜態數據
我已經將靜態變量放在一個單例中,並將其聲明爲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.
你能發佈一段代碼來顯示你的錯誤嗎? – MoRe 2012-07-16 11:28:48
小心分享您的代碼?我沒有看到您所描述的方法存在問題 – Miquel 2012-07-16 11:28:55
您是否可以詳細說明一下,如果可能的話用一些小例子? – Thomas 2012-07-16 11:29:43