안녕하세요 저는 동시성에 초보자이므로 future.isDone() 메서드가 true를 표시하는지 여부를 스레드 완료시 확인하는 매우 기본적인 프로그램을 작성했습니다. , 불행히도 scheduledAtFixedRate 메서드를 사용하여 작업을 예약 할 때 항상 "false"를 표시합니다. 그러나 일정 방법을 사용하면 "true"로 표시되지만 간단한 작업은 초 후에 다시 실행되지 않습니다. 왜 이런 경우인지 이해하는 데 도움이되는 제안이나 설명은 많은 도움이 될 것입니다.Executor.scheduleAtFixedRate 메서드를 사용할 때 Future.isDone()이 상태 변경을 표시하지 않음
감사합니다. 코드와 여기에
:
package com.company;
import org.testng.annotations.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
public class Main {
public static void main(String[] args) {
Main mn = new Main();
System.out.println("Main thread started...");
mn.runobjects();
System.out.println("Main thread stopping...");
}
@Test
public void runobjects(){
List<commonrun> Obj = new ArrayList<>();
Obj.add(new TestObj1());
Obj.add(new TestObj2());
Obj.add(new TestObj3());
ScheduledExecutorService executor = Executors.newScheduledThreadPool(5);
ScheduledFuture<?> futures1 = null;
ScheduledFuture<?> futures2 = null;
ScheduledFuture<?> futures3 = null;
int i=0;
for (commonrun obj : Obj){
if (i==0) {
futures1 = executor.schedule(() -> obj.runme(), 0, TimeUnit.SECONDS);
}
if (i==1) {
futures2 = executor.scheduleAtFixedRate(() -> obj.runme(), 0, 10, TimeUnit.SECONDS);
}
if (i==2) {
futures3 = executor.scheduleAtFixedRate(() -> obj.runme(), 0, 10, TimeUnit.SECONDS);
}
i++;
}
while(true){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread 1 is done : "+ futures1.isDone());
System.out.println("Thread 2 is done : "+ futures2.isDone());
System.out.println("Thread 3 is done : "+ futures3.isDone());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
package com.company;
public interface commonrun {
public void runme();
}
package com.company;
public class TestObj1 implements commonrun {
static int counter = 0;
@Override
public void runme() {
System.out.println("Object 1 Starting... run : " + counter);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Object 1 Stopping... run : " + counter);
counter++;
}
}
package com.company;
public class TestObj2 implements commonrun {
@Override
public void runme() {
System.out.println("Object 2 Starting...");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Object 2 Stopping...");
}
}
package com.company;
public class TestObj3 implements commonrun {
@Override
public void runme() {
System.out.println("Object 3 Starting...");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Object 3 Stopping...");
}
}
"executor.scheduleAtFixedRate()"를 사용하면 Future-Objects가 반환되지 않기 때문입니다. 이 결정은 작업이 실행될 때마다 메서드가 새로운 Future-Object를 반환하기 때문에 이루어졌습니다. 그리고 아무도이 작업이 얼마나 자주 실행되는지 알지 못하기 때문에 Java 설계자는이 홍수를 사전에 방지하기로 결정했습니다. – DiabolicWords