欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

多线程操作同一个数组,计算数组元素之和

程序员文章站 2024-01-26 08:55:05
...

利用CountDownLatch传入具体的参数。这个参数可以认为是线程的次数(计数器)。每次执行完计数器都会减1.直到为0,主线程开始执行。

public class FiveThreadCount {
	private int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
			27, 28 };
	private int total = 0;
	public static void main(String[] args) throws InterruptedException{
		FiveThreadCount threadCount=new FiveThreadCount();
		threadCount.test();	
	}
	public void test() throws InterruptedException {
		int length = arr.length;
		CountDownLatch latch = new CountDownLatch(length % 5 == 0 ? 5 : 6);
		System.out.println("length:" + length + ":" + "latch:" + latch.getCount());
		for (int j = 0; j < length; j += length / 5) {
			MyThread m = null;
			if ((j + (length / 5)) <= length) {
				m = new MyThread(arr, j, j + length / 5, latch);
			} else {
				m = new MyThread(arr, j, length, latch);
			}
			new Thread(m).start();
            latch.await();
            System.out.println(total);
		}
	}
	public class MyThread implements Runnable {
		int[] arr;
		int startIndex;
		int endIndex;
		CountDownLatch latch;

		public MyThread(int[] arr, int startIndex, int endIndex, CountDownLatch latch) {
			this.arr = arr;
			this.startIndex = startIndex;
			this.endIndex = endIndex;
			this.latch = latch;
		}

		@Override
		public void run() {
			int sum = 0;
			for (int i = startIndex; i < endIndex; i++) {
				sum += arr[i];
			}
			synchronized (MyThread.class) {
				total += sum;
			}
			System.out.println(Thread.currentThread().getName());
			latch.countDown();
		}
	}

}