문제

I have 5 threads running in an infinite loop. I need to fetch the final value after all 5 threads end every time. How can I do this?

while(true){
        new Class1(1,10).start();
        new Class1(11,20).start();
        new Class1(21,30).start();
        new Class1(31,40).start();
        new Class1(41,50).start();
    }

I need to determine the end of these 5 threads and pick one particular value updated in all the threads. How can I do this?

도움이 되었습니까?

해결책

Your code here is going to start 5 new threads every single time around the loop and keep looping constantly. Are you absolutely sure that's what you want?

Just use a CountDownLatch http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/CountDownLatch.html

Initialize the latch at 5. Each thread counts the latch down once when it exits.

The main thread waits for the latch to hit 0 then does its processing and exits.

Do not loop creating threads!

다른 팁

while(true){
  List<Class1> x = Arrays.asList( new Class1(1,10), new Class1(11,20), new Class1(21,30), new Class1(31,40), Class1(41,50));
  for (Class1 t: x) {
    x.start();
  }
  for (Class1 t: x) {
    x.join();
  }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top