2014-05-15 2 views
1

총 내 프로그램에서 작성한 모든 스레드를 계산하려고하는데 내 코드는 호출 시간 만 계산합니다. 출력에 난 모든 스레드가 내 멀티 스레드 프로그램의 실행 시간을 계산하는 방법

아래에있는 내 주요 프로그램 RequestProcessor가 여기 내 스레드 클래스 아래

int i = 0; 
List<Customer>customers = customer.getCustomers(); 
long startTimestamp = System.currentTimeMillis(); 
for (Customer c: customers){ 
    new RequestProcessor(c, i).start(); 
    i++; 
} 
long endTimestamp = System.currentTimeMillis(); 
System.out.println("difference = "+(endTimestamp - startTimestamp)); 

입니다

를 완료하기 전에 차이가 인쇄 참조 요청 프로세서 클래스

때문에

나는 확신 아래

public RequestProcessor(Customer customer , int threadSeq) { 
    super(); 
    this.customer = customer; 
    this.threadSeq = threadSeq; 
} 

@Override 
public void run() { 
    // TODO Auto-generated method stub 
    processRequest(); 
    super.run(); 
} 

public void processRequest(){ 
    //performing execution on customer here 
    System.out.println("processing "+ customer.getName()+" thread seq "+threadSeq); 
} 

내가

를 받고 오전 출력입니다
processing customer9 thread seq 9 
processing customer7 thread seq 7 
difference = 4 
processing customer3 thread seq 3 
processing customer2 thread seq 2 

나는 조인을 사용하려했지만 스레드의 특정 번호는 다음 실행 시간을 인쇄 할 수 있습니다 지적하는 countDown()를 호출 할 때까지 기다려야하는 CountDownLatch을 사용할 수 있습니다

답변

1

CountDownLatch을 사용할 수 있습니다. 중요한 동시 도구 클래스입니다. 자바 다중 스레드 프로그램에 대해 더 알고 싶다면. 책 연습에 자바 동시성 [브라이언 게츠]

int i = 0; 
    List<Customer>customers = customer.getCustomers(); 
    CountDownLatch cdl =new CountDownLatch(customers.size());  // new code 
    long startTimestamp = System.currentTimeMillis(); 

    for (Customer c: customers){ 
     new RequestProcessor(cdl,c, i).start(); 
     i++; 
    } 

    cdl.await();              // new code . 
    // the thread will hang up unitl all RequestProcessor run cdl.countDown() ; 
    long endTimestamp = System.currentTimeMillis(); 
    System.out.println("difference = "+(endTimestamp - startTimestamp)); 

RequestProcessor.class

public RequestProcessor(CountDownLatch cdl, Customer customer , int threadSeq) { 
     super(); 
     this.customer = customer; 
     this.threadSeq = threadSeq; 
     this.cdl=cdl;           // new code 
     } 
    @Override 
    public void run() { 
     // TODO Auto-generated method stub 
     processRequest(); 
     super.run(); 
     cdl.countDown();           // new code 
    } 
참조
1

나를 위해 작동하지 않았다. countDown() 메서드를 제대로 호출 할 수 있도록 Customer 클래스를 변경하여 CountDownLatch 개체를 가져와야하지만 일단 그렇게하면 제대로 작동합니다.

뭔가처럼 : 당신이 countDown()를 호출 할 때까지 당신이 만든 각 스레드를 하나 개의 래치 블록을함으로써 더 나은 시간을 얻을 수 있도록

CountDownLatch latch = new CountDownLatch(customers.size()); 
long startTimestamp = System.currentTimeMillis(); 
for (Customer c: customers){ 
    new RequestProcessor(c, i++, latch).start(); 
} 
latch.await(); 
// have each thread call countDown() after it's done, etc. 

두 래치를 가진 같은 것을 조금 더 복잡한 작업을 수행해야 할 수도 있습니다 주 스레드,하지만 그건 일반적인 생각입니다.

관련 문제