Question: Task B: Synchronization - (5 marks) Open the original file MultiThreading.java in NetBeans and run the original calculation loop using four threads simultaneously, make a

Task B: Synchronization - (5 marks) Open the original file MultiThreading.java in NetBeans and run the original calculation loop using four threads simultaneously, make a note of the total time taken for the program to run. Now modify the original file so that each thread performs the calculation loop in turn not in parallel (Hint: use the synchronized keyword). Again note the total time for the program to run. Compare the total time taken for both programs to run. Provide an explanation for your observations of the running times.

/* * Multi-Threading application * */ package multithreading;

import java.util.Random;

public class MultiThreading extends Thread {

private int id; // thread number

private static double[] shareddata; public MultiThreading(int i) { id = i; }

/* run method of the thread */ public void run() { int a;

Random generator = new Random(); long t = System.currentTimeMillis()/1000; for (a=0; a < 100000000; a++) { shareddata[a]=Math.cos(a+Math.sqrt(a*generator.nextDouble())); } System.out.println("Thread " + id + " took " + (System.currentTimeMillis()/1000 - t) + " seconds");

}

public static void main(String[] args) { // number of threads final int N = 1; shareddata = new double[100000000]; // System.out.println("Starting Multi-threading...");

// creating thread array MultiThreading[] thread = new MultiThreading[N];

for (int i = 0; i < N; i++) { /* initialise each thread */ thread[i] = new MultiThreading(i+1); /* start each thread */ thread[i].start(); } } }

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!