java HW 6.2

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java HW 6.2相关的知识,希望对你有一定的参考价值。

package com.gmail.vhrushyn;

public class MySummArray implements Runnable {

	private int[] intArr;
	private int[] summ;
	private int from;
	private int to;

	public MySummArray() {
		super();
		// TODO Auto-generated constructor stub
	}

	public MySummArray(int[] intArr, int[] summ, int from, int to) {
		super();
		this.intArr = intArr;
		this.summ = summ;
		this.from = from;
		this.to = to;
	}

	@Override
	public void run() {
	mySum();
	}

	private void mySum () {	
		int sum = 0;
		try {
		for (int i = from; i < to; i++) {
			sum += intArr[i];
		}
		} catch (ArrayIndexOutOfBoundsException e) {
			; // skip out of bounds 
		}
		summ[Integer.parseInt(Thread.currentThread().getName())] = sum;
	//	System.out.println("thread sum = "+sum);
	}
}
package com.gmail.vhrushyn;

import java.util.Date;
import java.util.Random;

public class Main {
	public static void main(String[] args) {

		int[] intArr = new int[20000000];

		Random rd = new Random();
		for (int i = 0; i < intArr.length; i++) {
			intArr[i] = rd.nextInt(10);
		}

		Date startThread = new Date();

		int qC = (Runtime.getRuntime().availableProcessors()) * 2; 

		int[] summ = new int[qC];

		int from = 0;
		int to = (intArr.length / qC) + 1;
		int c = 0;

		for (int i = 0; i < qC; i++) {

			Thread t = new Thread(new MySummArray(intArr, summ, from, to), "" + i + "");
			t.start();

			from = to;
			to += (intArr.length / qC) + 1;
			c = c + 1;
			try {
				t.join();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}

		}
		int sum = 0;
		for (int i : summ)
			sum += i;

		Date stopThread = new Date();

		long speedThread = stopThread.getTime() - startThread.getTime();

		System.out.println("time in multy-thread way = " + speedThread+" millis, " + " sum = " + sum);

		Date startRegular = new Date();
		int sumTwo = 0;
		for (int i = 0; i < intArr.length; i++) {
			sumTwo += intArr[i];
		}
		Date stopRegular = new Date();
		long speedRegular = stopRegular.getTime() - startRegular.getTime();

		System.out.println("time in regular way = " + speedRegular+" millis, " + " sum = " + sumTwo);

	}
}

以上是关于java HW 6.2的主要内容,如果未能解决你的问题,请参考以下文章

java HW05

java HW 10.4

java HW 7.2

java HW 7.3

java HW 7.1

java HW 5.3-5.4