2015-07-12 5 views
0

Supposons que j'ai la classe suivante, comment puis-je forcer l'exécution successive des trois threads l'un après l'autre successivement? (En attente de l'autre pour être mis fin)Exécuter des threads en séquence

public class MyRunnable implements Runnable{ 

    @Override 
    public void run() { 

     System.out.println("Thread 1 :First Thread started"); 
    } 

    public static Runnable delay(){ 
     Runnable r = new Runnable(){ 

      @Override 
      public void run() { // running state 

       System.out.println("Thread 2: loading second thread.."); 
       try { 
        Thread.sleep(2000); 
       } catch (InterruptedException e) { 
        e.printStackTrace(); 
       } 
       System.out.println("Thread 2: System loaded"); 
      } 

     }; // finished state 
     return r; 
    } 

    public static Runnable waiting(){ 
     Runnable r = new Runnable(){ 

      @Override 
      public void run() { // running state 

       System.out.println("Thread 3: waiting.."); 
       try { 
        Thread.sleep(5000); 
       } catch (InterruptedException e) { 
        e.printStackTrace(); 
       } 
       System.out.println("Thread 3: OK"); 

      } 

     }; // finished state 
     return r; 
    } 


    public static void main(String[] args) throws InterruptedException{ 

     Thread thread1 = new Thread(new MyRunnable());  
     Thread thread2 = new Thread(delay()); 
     Thread thread3 = new Thread(waiting()); // (initial state) 

     thread1.start(); 
     thread2.start(); 
     thread3.start(); 

    } 


} 
+8

La question est pourquoi? Si vous voulez que les opérations se déroulent en séquence, vous n'avez pas besoin de threads, écrivez simplement les opérations les unes après les autres dans la même méthode. – RealSkeptic

+0

En fait, il y a aussi des avantages révélés, je ne sais pas pourquoi ... Cochez cette réponse ---> https://stackoverflow.com/questions/30885037/multithreading-using-blocking-io-corrupts-file- in-java/30919133 # 30919133 @RealSkeptic –

+0

@shekharsuman Quelque chose de plus sérieux est nécessaire comme preuve. Le code de référence réel, par exemple. Et un exemple simplifié qui peut être exécuté n'importe où. – RealSkeptic

Répondre

2

Oui, il y a, mais pourquoi voulez-vous le faire?

public static void main(String[] args) throws InterruptedException{ 

    Thread thread1 = new Thread(new MyRunnable());  
    Thread thread2 = new Thread(delay()); 
    Thread thread3 = new Thread(waiting()); // (initial state) 

    thread1.start(); 
    thread1.join(); 
    thread2.start(); 
    thread2.join(); 
    thread3.start(); 
    thread3.join(); 
} 

Autre moyen (sans fils):

public static void main(String[] args) throws InterruptedException{ 

    new MyRunnable().run(); 
    delay().run(); 
    waiting().run(); 
} 

Votre code faites ceci:

Main thread  thread-1  thread-2  thread-3 
    V 
    | 
    + . . . . . . > V 
    + . . . . . . . | . . . . . . > V 
    + . . . . . . . | . . . . . . . | . . . . . . > V 
    X    |    |    | 
        X    |    | 
            |    | 
            X    | 
                | 
                X  

Vous avez demandé ce (il n'a pas de sens de faire parce que les threads peuvent paralléliser les tâches, et vous ne veulent pas les paralléliser!):

Main thread  thread-1  thread-2  thread-3 
    V 
    | 
    + . . . . . . > V 
    |    | 
    |<--------------X 
    + . . . . . . . . . . . . . . > V 
    |        | 
    |        | 
    |        | 
    |        | 
    |<------------------------------X 
    + . . . . . . . . . . . . . . . . . . . . . . > V 
    |            | 
    |            | 
    |            | 
    |            | 
    |            | 
    |            | 
    |<----------------------------------------------X 
    X 
+0

Je suis totalement nouveau avec les threads et je développe une application multi-threading, la question ci-dessus est juste un exemple pour comprendre comment ça marche, Merci pour votre réponse! –

+0

@johnnymanolly édité avec une explication. –

0

Mettez thread.join() après avoir démarré le fil. Cela attendra le thread pour revenir avant le prochain thread démarre.