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
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started