이것은 매우 간단한 질문 일 수 있지만 시도한 사항이 작동하지 않는 것 같습니다.함수에서 사용할 수있는 스레드에서 변수 가져 오기
편집 전체 코드를 보여주기 위해 : 나는
public MockDataGenerator() {
new Thread() {
@Override
public void run() {
while (true) {
try {
if (bayeuxIds.size() > 0) {
System.out.println("These are the bayeuxIds from new Thread" + bayeuxIds);
List<String> users = new ArrayList<String>();
users.addAll(bayeuxIds);
setData(users);
Collections.shuffle(users);
String bayeuxId = users.get(0);
List<Alert> alerts = generateRandomAlerts(1);
alertsAdded(bayeuxId, alerts);
}
} catch (Throwable t) {
} finally {
try {
int numUsers = bayeuxIds.size();
// plus 1 prevents divide by zero
sleep(30000);
//sleep(r.nextInt(120000/(numUsers + 1)));
} catch (InterruptedException e) {
}
}
}
}
}.start();
}
public void onMessage(Message message) {
System.out.println("Message recieved from ActiveMQ");
if (message instanceof TextMessage) {
try {
System.out.println("This is the 0th element of usersCopy: " + users.get(0));
String bayeuxId = users.get(0);
String theMsg = ((TextMessage) message).getText();
clientMessanger.sendUpdate(theMsg, bayeuxId);
} catch (Exception e) {
e.printStackTrace();
}
} else {
throw new IllegalArgumentException("Message must be of type TextMessage");
}
}
편집 1, 자바에 대한 이해가 잘되지 않습니다이 그래서 여기 간다, 내가 Threads
와 함께 작업 한 것은 이번이 처음이다 인정 , 기본적으로 내가 원하는 것은 스레드에서 사용자 목록을 onMessage 함수로 전달하는 것입니다. 나는 getters와 setters를 시도했지만 올바르게 작동하려면 syncronized 함수를 사용해야한다고 가정하기 때문에 작동하지 않았다?
편집 2 :
이러한 기능을 추가하지만 여전히 오른쪽 변수를 설정하지 않는 것. 내가 도대체 뭘 잘못하고있는 겁니까?
String bayeuxIdCopy;
public synchronized void setData(String bayeuxId) {
System.out.println("This is the bayeuxID being set: " + bayeuxId);
bayeuxIdCopy = bayeuxId;
}
public synchronized String getData() {
System.out.println("This is the bayeuxID being returned: " + bayeuxIdCopy);
return bayeuxIdCopy;
}
누락 된 항목이 있습니다.이 항목이 없으면이 질문을 이해하기 어렵습니다. 왜'generateRandom()'이 쓰레드에 싸여 있습니까? 스레드를 실행하면 한 번 실행되고 종료됩니다 ... 내부적으로 무한 루프를 수행합니다.이 경우 값을 검색 할 때 어떻게 나타낼 수 있습니까? 스레드를 시작하는 코드는 어디에 있습니까? 두 번째 코드 블록은 첫 번째 코드 블록과 어떤 관련이 있습니까? 연결이없는 것 같습니다. –
@JimGarrison 지금 전체 코드를 추가했습니다. 잘하면 지금은 이해가됩니다. 내가하지 못한다면 최선을 다할 것입니다. –
스레드 (내부 클래스와 onMessage 메서드 이후)에서 볼 수있는 클래스 수준 변수를 사용하십시오. 주어진 시간에 여러 스레드가 목록을 편집하지 않도록 동기화 된 컬렉션 클래스를 사용할 수 있습니다. –