그래, 모든 메소드가 스레드에서 실행되어야하는 Java 클래스가 있습니다. 하나의 스레드 만 시간과 특정 시간에 실행됩니다. Thread를 확장하는 내부 클래스로 이와 같이 구현했습니다.스레드 대기열을 가져 오는 데 걸리는 시간을 수정하십시오.
private void fetchTasks() {
new Thread() {
@Override
public void run() {
while(true) {
if(currentOperation == null && !operationList.isEmpty()) {
currentOperation = getOperation();
while(currentOperation.scheduledStartTime > System.currentTimeMillis()) {
// do nothing, wait for proper time;
}
currentOperation.start();
}
}
}
}.start();
}
private MyOperation getOperation() {
synchronized (operationList) {
return operationList.remove();
}
}
내가 큐에 스레드를 추가 해요 : 다음
private class MyOperation extends Thread {
public static final String M1 = "method1";
public static final String M2 = "method2";
public static final String M3 = "method3";
protected long scheduledStartTime = 0;
private String type;
public MyOperation(String type, long milliSecondsToWait) {
this.type = type;
scheduledStartTime = System.currentTimeMillis() + mlliSecondsToWait;
}
@Override
public void run() {
switch(type){
case M1:
doMethod1();
break;
case M2:
doMethod3();
break;
case M3:
doMethod3();
break;
}
setCurrentOperation(null);
}
}
private void setCurrentOperation(MyOperation task) {
synchronized (currentOperation) {
this.currentOperation = task;
}
}
나는 스레드 큐 현재 실행중인 스레드 같은
private MyOperation currentOperation;
private Queue <MyOperation> operationList;
내가 가져 오는거야 작업이 예를 들면 다음과 같습니다.
addOperation(new MyOperation(M1, 5));
private void addOperation(MyOperation task) {
synchronized (operationList) {
operationList.add(task);
}
}
내 질문 :
다른 스레드에서 각 메소드를 실행하는 더 좋은 방법이 있습니까?
스레드 큐를 올바르게 가져 오는 방법이 맞습니까?
당신에게 그냥 작은 일을
switch 문은 다형성에 대한 절박한 외침과 같습니다. 생성자에 'type'인수를 허용하는 하나의 MyOperation 클래스 대신 공통 인터페이스를 구현하거나 공통 추상 클래스에서 상속하는 세 가지 다른 MyOperationXxxxxx 클래스를 사용하는 것이 좋습니다. 즉, Java 유형을 사용하여 응용 프로그램의 '유형'개념을 표현하는 것이 어떻습니까? –
그래, 나는 이것이 일종의 추악한 데 동의한다. 기본적으로 클래스의 모든 메소드가 다른 스레드에서 실행되도록하기 때문에이 작업을 수행했습니다. 또한 "setCurrentOperation (null)"때문에 run() 메서드의 끝에서 호출해야합니다 – Manza