1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| public class Demo {
public static void main(String[] args) {
final ScheduledExecutorService executor = Executors.newScheduledThreadPool(5);
ScheduledFuture<?> task1 = executor.scheduleAtFixedRate(()-> System.out.println("s'affiche toutes les trois secondes"), 3, 3, TimeUnit.SECONDS);
pause(2);
AtomicInteger compteur=new AtomicInteger(0);
executor.scheduleAtFixedRate(compteur::incrementAndGet, 1, 1, TimeUnit.SECONDS);
ScheduledFuture<?> task2 = executor.scheduleAtFixedRate(()-> System.out.println("s'affiche toutes les secondes"), 1, 1, TimeUnit.SECONDS);
pause(2);
executor.scheduleAtFixedRate(Demo::uneMethode, 500, 500, TimeUnit.MILLISECONDS);
task1.cancel(true);
pause(2);
task2.cancel(true);
executor.scheduleAtFixedRate(()-> System.out.println("s'affiche toutes les quatres secondes"), 0, 4, TimeUnit.SECONDS);
executor.scheduleAtFixedRate(()-> System.out.println("Au fait, le compteur en est à " + compteur.get()), 0, 10, TimeUnit.SECONDS);
pause(30);
executor.shutdownNow();
System.out.println("Et on a compté pendant tout ce temps : " + compteur.get());
}
private static void uneMethode() {
System.out.println("Une tâche qui fait des trucs...");
}
private static void pause(int i) {
try {
Thread.sleep(i*1000);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
} |
Partager