내 설정은 설명 된대로입니다. 내가 성취하고자하는 것은 각 구현 클래스에있는 메소드를 병렬로 실행하는 것입니다. 내가 Future
과 Runnable
을 사용하는 것으로 들여다 보았습니다. 어느 과정으로 진행할 지 확신 할 수 없습니다.다른 스레드로 동시에 객체 내에서 메소드를 실행하는 방법은 무엇입니까?
내 첫 번째 생각은 boolean
대신에 Future<Boolean>
을 반환하려고했지만 처음에 호출 된 이름과 결과를 어떻게 연관시키는 지 확신 할 수 없습니다.
aMethod가 병렬/비동기로 실행되도록하려는 이유는 aMethod가 http 요청을 가질 수 있기 때문입니다. 요청이있는 경우 응답을 계속할 때까지 기다리지 않으려 고합니다. 나는 그것을 별도의 스레드에서 수행하고 다음 메소드로 계속 진행하기를 원한다.
많은 HTTP 요청이 있으면 aClass.doMethod()가 완료되는 데 시간이 걸립니다. 계속하기 전에 각 HTTP 요청을 기다릴 필요가 없도록 병렬로 실행하고 싶습니다.
누구든지이 작업을 수행하는 방법에 대한 정보를 얻을 수 있습니까?
import java.util.ArrayList;
import java.util.List;
//Strategy.java
public interface Strategy {
boolean aMethod();
}
//AStrategy.java
public class AStrategy implements Strategy {
@Override
public boolean aMethod() {
// Do a couple http requests
return true;
}
}
//BStrategy.java
public class BStrategy implements Strategy {
@Override
public boolean aMethod() {
// Do some other requests
return true;
}
}
//SomeClass.java
public class SomeClass {
String name;
Strategy aStrategy;
public SomeClass(String name, Strategy strategy) {
this.name = name;
this.aStrategy = strategy;
}
public boolean doMethod() {
return aStrategy.aMethod();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
//Just a regular pojo
//ResultsClass.java
public class ResultsClass {
String name;
boolean result;
public ResultsClass(String name, boolean result) {
this.name = name;
this.result = result;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isResult() {
return result;
}
public void setResult(boolean result) {
this.result = result;
}
}
public class AClass {
public static void main(String args[]) {
List<SomeClass> classes = new ArrayList<>();
classes.add(new SomeClass("Class 1", new AStrategy()));
classes.add(new SomeClass("Class 2", new BStrategy()));
List<ResultsClass> results = new ArrayList<>();
classes.forEach(aClass -> results.add(new ResultsClass(aClass.getName(), aClass.doMethod())));
}
}
당신이 실제로 요구하고있는 것이 명확하지 않습니다. 그리고 당신의 소스 코드는 유효하지 않은 java 구문을 가진 ** full **입니다. 진지하게 뒤로 물러서 야합니다. 예를 들어 컴파일하고 실행하는 예제를 작성하여 시작하십시오. 해결하려는 문제를 보여줍니다. 그리고 정직하게 말하면 : 구문 론적으로 올바른 자바 프로그램을 작성하는 방법을 아직 이해하지 못한다면, 지금 멀티 스레딩을 잊어 버리십시오. 실행하기 전에 크롤링하는 법을 배웁니다. – GhostCat
구문이 누락되어 죄송합니다 ... 저는 무엇을하고 있었는지 기억하기 위해 질문을 작성하는 것과 다른 것을 작성하는 사이를 전환하는 멀티 태스킹을 시도했습니다. 나는 그것이 편집되도록 그것을 편집했다 .... – TheBlueMan