2016-07-19 2 views
0

J'ai planifié une tâche récurrente. Maintenant, je veux que le thread principal attende le ScheduledExecutorService pour terminer son première exécution. Comment puis-je accomplir cela?Comment puis-je attendre la fin de la première itération d'une tâche planifiée?

public void test1(){ 
    refreshFunction(); /* This should block until task has executed once. */ 
    /* Continue with main thread. */ 
    ... 
} 

public void refreshFunction() { 
    try { 
    scheduledExecutorService = Executors.newScheduledThreadPool(1); 
    scheduledExecutorService.scheduleAtFixedRate(new Runnable() { 
     @Override 
     public void run() { 
     loadInfo(); 
     } 
    }, 1, 5, TimeUnit.MINUTES); 
    logger.info(" : Completed refreshing information : " 
     + new Timestamp(System.currentTimeMillis())); 
    } catch (Exception ex) { 
    ex.printStackTrace(); 
    } 
} 
+0

Vérifiez ma réponse dans: http://stackoverflow.com/questions/35075886/how-to-wait-for-a-thread-that-spawns-its-own-thread –

+0

Avez-vous vu ce 'schedExecutorService. awaitTermination (timeout, unité) '? – mob41

Répondre

2

Utilisez un CountDownLatch pour coordonner les fils.

final CountDownLatch latch = new CountDownLatch(1); 
scheduledExecutorService.scheduleAtFixedRate(new Runnable() { 
    @Override 
    public void run() { 
    loadInfo(); 
    latch.countDown(); 
    } 
}, 1, 5, TimeUnit.MINUTES); 
latch.await(); 

Une meilleure approche pourrait être la tâche planifiée pour exécuter un rappel après les informations sont chargées de mettre à jour les observateurs qui dépendent de ces informations.