1
스레드가 섞여 가고 있습니다. sendResult()
과 receiveResponse()
의 결과는 모두 다른 응답을 가져야합니다 (서블릿에서 JSON으로 응답 함). 그러나 응답자는 모두 sendResult()
이라는 응답으로 응답합니다.스레드가 섞여 있습니다
누군가가 이것이 왜이며 어떻게 해결할 수 있는지 설명 할 수 있습니까?
class Authenticate {
String t2RequestId = null;
String finalUserInput = null;
public synchronized String sendAuthentication(String deviceId, String requestId, String apiKey) {
// Send notification
GCM gcmClass = new GCM();
gcmClass.authenticateRequest(deviceId, requestId, apiKey);
while(!t2RequestId.equals(requestId)) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return finalUserInput;
}
public synchronized void receiveAuthentication(String userInput, String requestId) {
finalUserInput = userInput;
t2RequestId = requestId;
notifyAll();
}
}
class T1 implements Runnable {
Authenticate m;
private final String deviceId;
private final String requestId;
private final String apiKey;
String result;
public T1(Authenticate m1, String deviceId, String requestId, String apiKey) {
this.m = m1;
this.deviceId = deviceId;
this.requestId = requestId;
this.apiKey = apiKey;
Thread t1 = new Thread(this, requestId);
t1.start();
// Wait for thread to finish before sending response
try {
t1.join();
} catch(InterruptedException e) {
e.printStackTrace();
}
}
public void run() {
result = m.sendAuthentication(deviceId, requestId, apiKey);
}
public String getResult() {
return result;
}
}
class T2 implements Runnable {
Authenticate m;
private final String requestId;
private final String userInput;
public T2(Authenticate m2, String requestId, String userInput) {
this.m = m2;
this.requestId = requestId;
this.userInput = userInput;
Thread t2 = new Thread(this, "t2" + requestId);
t2.start();
}
public void run() {
m.receiveAuthentication(userInput, requestId);
}
}
public class AuthenticationHandler {
final static Authenticate m = new Authenticate();
public static String sendRequest(String deviceId, String requestId, String apiKey) {
T1 runnable = new T1(m, deviceId, requestId, apiKey);
String result = runnable.getResult();
return result;
}
public static void receiveResponse(String requestId, String userInput) {
new T2(m, requestId, userInput);
}
}
내가 이해하지 못하는 경우가 있습니다. T1이 초기화되고 주 스레드가 T1 스레드를 기다립니다. 그러나 T1 스레드는 응답을 기다리고 T2가 실행되지 않습니다. sendRequest 및 receiveResponse는 어디에서 호출합니까? –
서블릿에서 응답을 받으셨습니까? notify는 스레드를 임의로 알려주기 때문에 좋은 해결책이 아닙니다. 예를 들어 30 개의 스레드가 대기하고 있고 알림을 호출하면 무작위로 스레드를 선택합니다. –
또한 클래스에는 큰 문제가 될 수있는 상태가 있습니다. –