고정 변수가 아닌 정적 변수 데이터를 공유하는 두 개의 스레드가 있고 그에 따라 실행해야합니다. 그러나이 스레드 중 어느 것도 정적 변수에 대한 자체 상태를 유지하는 것 외에도 업데이트 된 정적 변수 데이터를 가져올 수 없습니다.정적 데이터를 공유하지 않는 Java 스레드
나는 하나의 변수에 정적 변수를 넣고 휘발성 변수로 선언했지만 여전히 결과는 동일합니다.
누군가가이 방법으로 문제를 제안 할 수 있으며이를 해결하기 위해 무엇을 할 수 있습니까? 당신이 그 상태를 돌연변이하려는 경우
들으, 싱글 휘발성에 참조를 선언 에이
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
코드를 공유하는 데주의해야합니까? 내가 설명한 접근 방식에 문제가 보이지 않는다. – Miquel
가능한 한 작은 예제로 좀 더 자세히 설명해 주시겠습니까? – Thomas