내 서비스에 대한 REST 호출이 새 스레드를 작성하는 백엔드 서비스를 구축 중입니다. 쓰레드가 죽을 때까지 5 분을 기다려서 아무 것도받지 못하면 쓰레드는 다른 REST 호출을 기다린다. 모든 스레드를 추적하려면 현재 실행중인 모든 스레드를 추적하는 컬렉션이 있으므로 REST 호출이 마침내 사용자가 동의하거나 거부 할 때와 같이 사용자 ID를 사용하여 해당 스레드를 식별 할 수 있습니다. 거부 된 경우 해당 스레드가 수락되어 다음 작업을 수행 할 수있는 경우 해당 스레드를 컬렉션에서 제거합니다. 동시성 문제를 피하기 위해 ConcurrentMap을 사용하여 구현했습니다.ConcurrentMap에 스레드를 저장하는 것이 안전합니까?
처음으로 스레드로 작업하기 때문에 발생할 수있는 문제가 간과되지 않도록하고 싶습니다. 제 코드를 살펴보고 더 잘할 수 있는지 또는 결함이 있는지 알려주세요.
public class UserAction extends Thread {
int userID;
boolean isAccepted = false;
boolean isDeclined = false;
long timeNow = System.currentTimeMillis();
long timeElapsed = timeNow + 50000;
public UserAction(int userID) {
this.userID = userID;
}
public void declineJob() {
this.isDeclined = true;
}
public void acceptJob() {
this.isAccepted = true;
}
public boolean waitForApproval(){
while (System.currentTimeMillis() < timeElapsed){
System.out.println("waiting for approval");
if (isAccepted) {
return true;
} else if (declined) {
return false;
}
}
return isAccepted;
}
@Override
public void run() {
if (!waitForApproval) {
// mustve timed out or user declined so remove from list and return thread immediately
tCollection.remove(userID);
// end the thread here
return;
}
// mustve been accepted so continue working
}
}
public class Controller {
public static ConcurrentHashMap<Integer, Thread> tCollection = new ConcurrentHashMap<>();
public static void main(String[] args) {
int barberID1 = 1;
int barberID2 = 2;
tCollection.put(barberID1, new UserAction(barberID1));
tCollection.put(barberID2, new UserAction(barberID2));
tCollection.get(barberID1).start();
tCollection.get(barberID2).start();
Thread.sleep(1000);
// simulate REST call accepting/declining job after 1 second. Usually this would be in a spring mvc RESTcontroller in a different class.
tCollection.get(barberID1).acceptJob();
tCollection.get(barberID2).declineJob();
}
}
'스레드 '를 확장하지 마십시오. 대신에'Runnable' 또는'Callable'을 구현하십시오. ExecutorService를 사용하여 실행하십시오. 당신은 방금 스레드를 사용하기 시작한 사람에게 너무 영리 해 지려고합니다. 'CompletableFuture'도 여기에 적합 할 수 있습니다. – Kayaman
코드가 어떻게 되었습니까? 컴파일 할 수 없습니다 (예 : '공공'은 없다. 입력 보조자가 자동 수정을 수행하는 휴대 전화에 입력 한 적이 있습니까? – Lothar
@Kayaman Yea 나는 물건을 더 복잡하게 만들고 있다고 나는 동의한다. ExecutorService를 사용하려고 생각했지만 나중에 스레드를 참조 할 수있게되어 작업을 수락 할 수 있습니까? – Claudiga