2014-04-25 8 views
0

누군가가 나를 도와 줄 수 있는지 궁금해했다.자바 쓰레드 사용하기, 반복적으로

나는 (자바를 사용하여) 달성하고 싶다 무엇 : 첫 번째 반복에서

, 나는 "doStuff"10 배 (동시에)에합니다.

두 번째 반복에서 첫 번째 반복이 완료된 후 20 번 (동시 방식으로) "doStuff"하고 싶습니다.

내 코드의 문제는 한 번에 물건을 30 번하고있어 것입니다

등 ... (I이 100 배를 할 계획 때문에 루프 수 있도록하고 싶습니다). 어떤 도움이라도 대단히 감사하겠습니다.

추신 : 간략화를 위해 코드 부분이 제거되었으므로 실수가있을 경우 알려주십시오.

public static void doStuff(){ 

[Code] 

} 

public static void threadThis (int y){ 

for (int i = 0; i<y; i++) { 
    Thread t1 = new Thread(){ 
     public void run() { 
      doStuff(); 
     } 
    }; 
    t1.start(); 
    } 

} 

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


    for (int p = 0; p<21; p = p + 10){ 
     threadThis(p); 
    } 
} 
+1

당신은 Fi를 한 후 실행의 20 "doStuff"의 두 번째 반복을 원하는 경우 첫째, 스레드의 두 번째 반복에 대한 보류를 구현해야합니다. 지금 당장은 아무것도하지 않기 때문에 호출 될 때 30 개의 스레드가 모두 실행되고 실행됩니다. – JWiley

+0

[fork-join] (http://docs.oracle.com/javase/tutorial/essential/concurrency/forkjoin.html) 자습서를 살펴보십시오. – Ralf

+0

Thread 클래스를 확장하는 클래스를 만들고 "doStuff()"함수가 끝나자 마자 boolean finished = true를 설정하십시오. 현재 실행중인 모든 스레드에 대한 루프를 체크 인하 고 완료 속성이 모두 참이면 다른 작업을 수행하는 10 개의 스레드를 추가로 만들 수 있습니다. – 1337

답변

1

당신은 threadThis을 변경할 수 있습니다() (가입하기) 모든 스레드가 그 시작 후.

public static void threadThis (int y){ 
    List<Thread> threads = Lists.newArrayListWithCapacity(y); 
    for (int i = 0; i<y; i++) { 
     Thread t1 = new Thread(){...}; 
     t1.start(); 
     threads.add(t1); 
    } 
    for (Thread t : threads) { 
     t.join(); 
    } 
} 
2

여기 java.util.concurrent의 패키지에서 CountDownLatch를 클래스에 대한 좋은 작업입니다.

자연스럽게 작업을 대기해야 큰 작업에 물적 분할, 정확히 CountDownLatch를 책임입니다. CountDownLatch API 문서에 대한

봐, 좋은 코드 샘플이, 사용자의 필요에 채택 easely 수

+0

또한 OP는 'CyclicBarrier'사용을 고려할 수 있습니다. –

0

다른 사람들이 말하는대로 CountDownLatch은 매우 유용합니다. CountDownLatch은 실제로 아래에 wai t 및 notify을 사용하고 있습니다. 그래서 이것은 waitnotif y를 작동시켜 유사한 기능을 구현하는 방법입니다.

홈페이지

public class Main 
{ 
    public static void main(String[] args) 
    { 
     Manager mgr = new Manager("manager"); 
     mgr.start(); 

    } 
} 

관리자

public class Manager extends Thread 
    { 
     public int threadCount=0; 

     private final Object lock = new Object(); 

     public Manager(String name){ 
      super(name); 
     } 


     public void pauseAndWaitForAll() 
     { 
      synchronized (this.lock) { 
        try { 
         while(this.threadCount>0) 
         { 
          this.lock.wait(); 
         } 
        } catch (InterruptedException e) { 
         e.printStackTrace(); 
        } 
      } 
     } 
     public void countDown() 
     { 
      synchronized (this.lock) { 
       this.threadCount--; 

// if the if block becomes uncommented notify will only be called 
// by last running thread of group, thus will only be called by last running thread of 
// group. If the if block is left commented out then every thread that is done with its 
// work will call notify and thus wait will be called again due to the 
// while(thread.count>0) loop not terminating 


          //if (this.threadCount <= 0) 
       //{ 
        this.lock.notify(); 
       //} 
      } 
     } 

     public void run() 
     { 
      for (int p = 10; p<1001; p = p + 10) 
      { 
       this.threadCount=p; 

       for (int i = 0; i<p; i++) 
       { 
        System.out.println(" new thread...: "+i+" "); 

        new DoWork(this,"thread: num:"+i+"--group:"+p).start(); 
       } 

       pauseAndWaitForAll(); 

       // uncomment the following for debugging 
    //   System.out.println(" ------------------next group-----------------------"); 
    //   try { 
    //    Thread.sleep(3000); 
    //   } catch (InterruptedException e) { 
    //    System.out.println(" pause error "); 
    //   } 
      } 
     } 
    } 

DoWork

public class DoWork extends Thread 
{ 
    private Manager managerThread; 

    public DoWork(Manager managerThread,String name){ 
     super(name); 

     this.managerThread=managerThread; 
    } 


    public void run() 
    { 
     try { 
//   System.out.print(this.getName()+" going to sleep ...: "); 
      int randSleep= 1000*(0 + (int)(Math.random() * ((5 - 0) + 1))); 
      Thread.sleep(randSleep); 
      System.out.println(this.getName()+" woke up ... "); 
     } catch (InterruptedException e) { 
      System.out.println(" worker thread: job simulation error:"+e); 
     } 

     managerThread.countDown(); 
    } 
} 
관련 문제