09/09: Lab – Java threading exercise

Inspiration from Jamie King’s Youtube tutorials on Threading – Divide and Conqueror Example. Instead of using C#, the below code is in Java (yay!).

import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;

public class ThreadExercise extends Thread {

	private final static Logger LOGGER = Logger.getLogger(ThreadExercise.class.getName());

	static int cores = Runtime.getRuntime().availableProcessors();

	final static int NUM_OF_VALUES =  cores * 55000000;
	static int[] values = new int[NUM_OF_VALUES]; 

	static int portionSize = values.length / cores;
	static int[] portionResults = new int[cores];
	private int portionNumber;

	public ThreadExercise(int portionNumber) {
		this.portionNumber = portionNumber;
	}

	public void run() {
		// Summing each portion in multi-thread
		int sum =0;
		int baseIndex = portionNumber * portionSize;
		for( int i=baseIndex; i<baseIndex + portionSize; i++) {
			sum += values[i];
		}
		portionResults[portionNumber] = sum;
		LOGGER.info(portionNumber + ": " + sum);
	}

	public static void generateInts() {
		Random randomGenerator = new Random();
		for( int i=0; i<values.length; i++ ) {
			int randomInt = randomGenerator.nextInt(10);
			values[i] = randomInt;
		}
	}

	public static void main(String args[]) {

		generateInts();
		LOGGER.setLevel(Level.OFF);

		/***********************************
				Using one thread
		************************************/
		{
			System.out.println("Summing with one thread");
			int total = 0;
			long startTime = System.currentTimeMillis();

			//summing
			for( int i=0; i<values.length; i++ ) {
				total += values[i];
			}

			long elapsedTime = System.currentTimeMillis() - startTime;

			System.out.println("Total value is: " + total);
			System.out.println("Time to sum: " + elapsedTime + " ms\n");
		}

		/***********************************
				Using multiple threads
		************************************/
		{
			System.out.println("Summing with multiple threads");
			int total = 0;
			long startTime = System.currentTimeMillis();

			Thread[] thread = new Thread[cores];

			// multi-threading: summing in each portion
			for( int i=0; i<cores; i++ ) {
				thread[i] = new ThreadExercise(i);
				thread[i].start();
			}

			// join threads to wait for all threads to be done
			// before proceeding the next step
			for( int i=0; i<cores; i++ ) {
				try {
					thread[i].join();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}

			// sum portion to compute final result
			for( int i=0; i<cores; i++ ) {
				total += portionResults[i];
			}

			long elapsedTime = System.currentTimeMillis() - startTime;

			System.out.println("Total value is: " + total);
			System.out.println("Time to sum: " + elapsedTime + " ms");
		}
	}
}

Output:

My system has 4 cores and here’s the result:

Summing with one thread
Total value is: 990026095
Time to sum: 101 ms

Summing with multiple threads
Total value is: 990026095
Time to sum: 76 ms

 

 

 

 

Advertisements