Created
September 25, 2017 17:34
-
-
Save Bresiu/d4e9d72caee5c9a29a47c669b3ec4056 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.concurrent.Executor; | |
import java.util.concurrent.Executors; | |
import java.util.concurrent.ScheduledExecutorService; | |
import java.util.concurrent.ScheduledFuture; | |
import java.util.concurrent.TimeUnit; | |
public class DelayedScheduleTest { | |
private static final int TASKS_NUMBER = 100; | |
private ScheduledExecutorService executor; | |
private ScheduledFuture<?> scheduledFuture; | |
private Executor singleExecutor; | |
public DelayedScheduleTest() { | |
executor = Executors.newSingleThreadScheduledExecutor(); | |
singleExecutor = Executors.newSingleThreadExecutor(); | |
} | |
private void execute() { | |
for (int i = 0; i < TASKS_NUMBER; i++) { | |
System.out.println("fire runnable: " + i); | |
scheduleRunnable(i); | |
} | |
} | |
private void scheduleRunnable(int i) { | |
singleExecutor.execute(() -> { | |
if (scheduledFuture != null) { | |
scheduledFuture.cancel(false); | |
} | |
scheduledFuture = executor.schedule((Runnable) () -> System.out.println("runnable: " + i), 5, | |
TimeUnit.SECONDS); | |
}); | |
} | |
public static void main(String[] args) { | |
DelayedScheduleTest delayedScheduleTest = new DelayedScheduleTest(); | |
delayedScheduleTest.execute(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment