使用多线程实现批处理过程,将一下数组,按10个一组,每组一个打印数据,并在19个线程都处理完成后输出打印次数 int[]data = new int [100]; for(int i=0;i <100;i++){data[i] =i;}
- import java.util.concurrent.CountDownLatch;
-
- public class BatchProcessing {
- public static void main(String[] args) {
- int[] data = new int[100];
- for (int i = 0; i < 100; i++) {
- data[i] = i;
- }
-
- int batchSize = 10;
- int numThreads = data.length / batchSize;
-
- CountDownLatch latch = new CountDownLatch(numThreads);
-
- for (int i = 0; i < numThreads; i++) {
- int startIndex = i * batchSize;
- int endIndex = Math.min((i + 1) * batchSize, data.length);
-
- Runnable task = new BatchProcessor(data, startIndex, endIndex, latch);
- Thread thread = new Thread(task);
- thread.start();
- }
-
- try {
- latch.await(); // 等待所有线程完成
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
-
- System.out.println("All threads have completed.");
- }
- }
-
- class BatchProcessor implements Runnable {
- private int[] data;
- private int startIndex;
- private int endIndex;
- private CountDownLatch latch;
-
- public BatchProcessor(int[] data, int startIndex, int endIndex, CountDownLatch latch) {
- this.data = data;
- this.startIndex = startIndex;
- this.endIndex = endIndex;
- this.latch = latch;
- }
-
- @Override
- public void run() {
- for (int i = startIndex; i < endIndex; i++) {
- System.out.println("Data: " + data[i]);
- }
- latch.countDown(); // 通知主线程任务已完成
- }
- }