I. Problem
    There are 100 thread need to be execute. but because of CPU and RAM size are too small. And If we want all thread need to wait unless all thread are finish execute and we want to get all result from those thread.

so what to do?

II. Solution

int num;
List<Integer> nums = new ArrayList<>();

@Test
public void testThreadAsys() {
System.out.println("-------start------");
ExecutorService executor = Executors.newFixedThreadPool(10);
final CountDownLatch countDownLatch = new CountDownLatch(100);

for(int i=0;i<100;i++){
executor.execute(new Runnable() {
@Override
public void run() {
System.out.println("-------running------");
num++;
nums.add(doRun());
countDownLatch.countDown();
}
});
}

try {
countDownLatch.await();
} catch (InterruptedException e1) {
e1.printStackTrace();
} finally {
executor.shutdown();
}



System.out.println("------- end------");

for(Integer n:nums){
System.out.println(""+n);
}
}

public int doRun(){
return num;
}

Post a Comment

 
Top