2011-01-24 2 views
1

대학 과제를 수행하고 있습니다 (솔직히 말해서). 문제는 4 개의 클라이언트 스레드가 언제든지 실행되어야한다는 것입니다 (n은 uptil입니다). 따라서 모든 스레드가 종료 될 때마다 새 스레드를 생성해야합니다.메인 스레드가 이벤트 대기 중임

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

    { 
    /* some declarations.. */ 

    ClientThread client=new ClientThread(); 

Runnable intr =client; 

for(count=1;count<=number;count++) 

{ 
       /* If 4 client threads has been spawned, wait until 1 of them exits */ 
      while(Thread.activeCount()<5) 
      ; 
      new Thread(intr).start(); 
    } 


     /* Wait until all other threads exits. */ 
     while(Thread.activeCount()!=1) 
     ; 

System.out.println("\n The sum of factorials is: "+client.getResult()); 
    } 

내 프로그램의 목적에 어긋나지 않으므로 바쁜 대기를 제거하고 싶습니다. 어떻게 메인 스레드를 만들 수 있습니다 wait ?? (wait은 정적이 아닌 메소드이므로 정적 메소드에서 호출 할 수 없습니다.) 도움을주십시오.

+0

멀티 스레딩 계산 계승을하지 않는 한 여러 스레드를 사용하는 것이 하나를 사용하는 것보다 느릴 수 있습니다. –

+0

나는 'n'숫자의 팩토리얼의 합을 계산해야한다 : 1! +2! + .. + n! 각 계승 계산은 (서버에 의해 다른 스레드를 통해) 독립적입니다. 여전히 느린가 ?? 제 교수가 말한 것을 구현하지 못했습니다. : -/ – letsc

답변

5

java.util.concurrent. CountDownLatch은 귀하의 케이스를 위해 설계되었습니다.

doneSignal.countDown()가 네 번 호출 될 때까지 기다립니다

doneSignal.await()CountDownLatch doneSignal = new CountDownLatch(4);을 정의합니다. 이 종료 될 때 ClientThreads가 doneSignal 참조를 보유하게하려면 doneSignal.countDown()으로 전화하십시오.

class ClientThread implements Runnable { 
    private final CountDownLatch doneSignal; 
    ClientThread (CountDownLatch doneSignal) { 
     this.doneSignal = doneSignal; 
    } 
    public void run() { 
     try { 
     //Do something 
     doneSignal.countDown(); 
     } catch (InterruptedException ex) {} 
    } 
} 
... 
//In main thread 
doneSignal.await(); 
+0

실제로 작동합니까?클라이언트 스레드가 메인 스레드를 종료 할 때마다 질문이 매번 다른 스레드를 생성해야한다고 생각하는 반면에 메인 스레드를 풀기 전에 종료 할 4 개의 스레드를 기다리는 것처럼 보입니다. –

-1

메인 쓰레드를 들어 당신이 사용할 수있는 모든 양산 스레드가 죽을 때까지 메인 스레드가 종료하기 전에

Thread.getCurrent().join(); 

이, 대기합니다.

5

흠 - 당신이 손으로 그것을해야하거나 Executors.newFixedThreadPool(4)을 발견 할 것을 선생님이 기대 않습니다합니까?

정확히 4 개의 작업 스레드가있는 스레드 풀이 수행 할 작업입니다. 4 개 이상의 클라이언트가 병렬로 실행되지 않습니다. 하나가 종료되면, 작업자 스레드는 "새로운 작업을 얻을 준비가되었습니다".


꽤 간단합니다

public void test(int threads, int runnables) { 
    ExecutorsService pool = Executors.newFixedThreadPool(threads); 
    Runnable r = new Runnable() { 
    public void run() { 
     // calculate a factorial or do something else 
     System.out.println(Thread.currenThread()); 
    } 
    } 
    for (int i = 0; i < runnables; i++) 
    pool.execute(r); 
} 

runnablesthreads 다음 더 큰하자 및 스레드의 최대 threads 수는 (재)를보다 Runnable을 실행하는 데 사용됩니다, 그 결과에서 볼 수 있습니다.

+0

그래서 Executors와 CountDownLatch 사이를 결정해야합니다 ... CountDownLatch는 구현하기가 매우 쉽습니다. – letsc

1

기본 스레드에서 콜백 메소드를 작성할 수 있습니다. 콜백 메소드는 기존 스레드에서 호출하고 새 스레드를 생성합니다. 메인 클래스의 정적 필드를 사용하여 현재 코드와 동일한 효과를 얻기 위해 스폰 된 스레드 수를 추적합니다.

는 다음과 같이 어떻게 든 보일 것이다

class Main{ 

    private static ClientThread client; 
    private static Runnable intr; 
    private static int count; 

    public static void main(String[] args) 
    { 
     count = 10; //Or something else 
     runningThreads = 0; 
     client=new ClientThread(); 
     intr =client; 
     for(i=0;i<5;i++) 
      spawnThread(); 
    } 

    private static void spawnThread() 
    { 
     Thread newThread; 
     if(count>0) 
     { 
      newThread = new Thread(intr); 
      newThread.start(); 
      count--; 
     } 

     if(count==0) 
      System.out.println("\n The sum of factorials is: "+client.getResult()); 
    } 
0

는 특히 java.util.concurrent.CountDownLatch java.util.concurrent.locks.Condition

java.util.concurrent의 의 모양 @ 클래스를 타고
관련 문제