Menu

Task B Synchronization 5 Marks Open Original File Multithreadingjava Netbeans Run Original Q43839276

Task B: Synchronization – (5 marks)
Open the original file MultiThreading.java in NetBeans and run theoriginal calculation loop using four threads simultaneously, make anote of the total time taken for the program to run.
Now modify the original file so that each thread performs thecalculation loop in turn not in parallel (Hint: use thesynchronized keyword). Again note the total time for the program torun. Compare the total time taken for both programs to run. Providean 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();
}
}
}

Expert Answer


Answer to Task B: Synchronization – (5 marks) Open the original file MultiThreading.java in NetBeans and run the original calculat…

OR