참고 : 이것은 장난감 코드이며 제작 준비가되지 않았습니다.작업에서 with with ScheduledExecutorService의 Runnable 작업 중지
모든 고정 지연 (예 : 2 초)을 실행하려면 MyTask
을 예약하고 싶습니다. 그리고이 일이 끝나면 스스로 멈추기를 원합니다. MyTask
에 대한 코드는 다음과 같습니다
public class MyTask implements Runnable {
MainClass parent;
AtomicInteger integer = new AtomicInteger(0);
public MyTask(MainClass parent) {
this.parent = parent;
}
@Override
public void run() {
try {
int valueNow = integer.incrementAndGet();
System.out.println("Running with value: " + valueNow + " and going to do work");
Thread.sleep((long)(Math.random() * 10000)); // simulate some work
System.out.println("Running with value: " + valueNow + " and work over");
if(valueNow == 5) {
parent.stopTask();
}
} catch (Exception exception) {
System.out.println("Interrupted");
}
}
}
그리고 MainClass
은 일정 그것을 하나입니다
public class MainClass {
private ScheduledExecutorService executorService;
private ScheduledFuture updateFuture;
public static void main(String[] args) {
new MainClass().startMyTask();
}
public void startMyTask() {
System.out.println("Starting MyTask to run every 2 seconds..............");
executorService = Executors.newScheduledThreadPool(2);
updateFuture = executorService.scheduleAtFixedRate(new MyTask(this), 1, 2, TimeUnit.SECONDS);
}
public void stopTask() {
System.out.println("Stopping MyTask to run further");
updateFuture.cancel(true);
}
}
이 시나리오를 재현 단지 장난감 코드입니다. 이 접근법에 문제가 있습니까? 어디서 멈출 수 있도록 부모에 대한 참조를 스레드에 전달합니까? 더 좋은 방법이 있습니까?
괜찮습니다. 무엇이 문제입니다? – canillas
@canillas 내 질문에 대한 접근 방식입니다. 작업 자체가 중단되기를 원한다면 더 나은 접근 방법이 있습니까? –