2009-12-15 27 views
17

Ben thread to thread. Çalışmak için t.join'u nasıl alabilirim?Java: Nasıl kullanılır: Thread.join

Bu kod programın donmasına neden olur, çünkü iş parçacığı kendini ölüme bekliyordur, değil mi?

public static void main(String[] args) throws InterruptedException { 
    Thread t0 = new Thready(); 
    t0.start(); 

} 

@Override 
public void run() { 
    for (String s : info) { 
     try { 
      join(); 
      Thread.sleep(1000); 
     } catch (InterruptedException e) { 
      e.printStackTrace(); 
     } 
     System.out.printf("%s %s%n", getName(), s); 
    } 
} 

ben biri daha sonra, yarım info dizi yazdırır diğer dinlenme yapmadan önce bitmesi için bekler iki konuları, sahip olmak isteseydiniz ne yapardınız? Böyle

cevap

18

Kullanım şey:

public void executeMultiThread(int numThreads) 
    throws Exception 
{ 
    List threads = new ArrayList(); 

    for (int i = 0; i < numThreads; i++) 
    { 
     Thread t = new Thread(new Runnable() 
     { 
      public void run() 
      { 
       // do your work 
      } 
     }); 

     // System.out.println("STARTING: " + t); 
     t.start(); 
     threads.add(t); 
    } 

    for (int i = 0; i < threads.size(); i++) 
    { 
     // Big number to wait so this can be debugged 
     // System.out.println("JOINING: " + threads.get(i)); 
     ((Thread)threads.get(i)).join(1000000); 
    } 
0

diğer konular üzerinde join yöntemi çağırmak zorundadır. gibi
şey: otherThread diğer konu olma ile

@Override 
public void run() { 
    String[] info = new String[] {"abc", "def", "ghi", "jkl"}; 

    Thread other = new OtherThread(); 
    other.start(); 

    for (int i = 0; i < info.length; i++) { 
     try { 
      if (i == info.length/2) { 
       other.join(); // wait for other to terminate 
      } 
      Thread.sleep(1000); 
     } catch (InterruptedException e) { 
      e.printStackTrace(); 
     } 
     System.out.printf("%s %s%n", getName(), info[i]); 
    }  
} 
4

, böyle bir şey yapabilirsiniz: Güneş'ten

@Override 
public void run() { 
    int i = 0; 
    int half = (info.size()/2); 

    for (String s : info) { 
     i++; 
     if (i == half) { 
     try { 
      otherThread.join(); 
     } catch (InterruptedException e) { 
      e.printStackTrace(); 
     } 
     System.out.printf("%s %s%n", getName(), s); 
     Thread.yield(); //Give other threads a chance to do their work 
    }  
} 

Java öğretici: http://java.sun.com/docs/books/tutorial/essential/concurrency/join.html

İlgili konular