4) Write a code fragment consisting of a single statement showing how to use the Integer wrapper class to convert a string containing digits to an integer and store it in a variable of type int.

5) When you declare an array in Java, the memory required to contain the array data is automatically allocated T/F? If false, explain why and show how memory can be allocated.

6) Write Java code to instantiate 12 objects of Circle and Square (both are subclasses of Shape) in an array and then print their areas (6 circles + 6 squares).

7) Write multithreading programs in Java to create three threads that will update array Y as follows. Given three arrays A, B, and Y of 12 integer elements each, and arrays A and B are filled with data, the three threads will fill array Y with the addition of the corresponding elements of A and B, that is: Y[i] = A[i] + B[i]. Use multithreading (using Runnable) with synchronization correctly.

8) Java Concurrency: (a) Run the program in Fig. 23.3 and 23.4 and provide two sample output/runs. (b) Run the programs (classes in Fig 23.5,6,7) and provide two sample output/runs as is {without synchronization add()} and then change the values 1 and 11 (to be added to the shared array) to 51 and 101 and provide two other sample runs. (c) Run the multithreading program in part (b) after making add() method synchronized and provide two runs; then change the values that are added into the array and provide two sample runs.

// Fig 23.23 PrintTask.java
// PrintTask class sleeps for a random time from 0 to 5 seconds
import java.security.SecureRandom;

public class PrintTask implements Runnable
{
private static final SecureRandom generator = new SecureRandom();
private final int sleepTime; // random sleep time for thread
private final String taskName;

// Constructor
public PrintTask(String taskName)
{
this.taskName = taskName;

// pick random sleep time between 0 and 5 seconds
sleepTime = generator.nextInt(5000); // milliseconds
}

// method run contains the code that a thread will execute
public void run()
{
try // put thread to sleep for sleepTime amount of time
{
System.out.printf("%s going to sleep for %d milliseconds.%n,
taskName, sleepTime);
Thread.sleep(sleepTime); // put thread to sleep
}
catch(InterruptedException exception)
{
exception.printStackTrace();
Thread.currentThread().interrupt(); // re-interrupt the thread
}

// print task name
System.out.printf("%s done sleeping%n", taskName);
}
} // end class PrintTask
// Fig. 23.4: TaskExecutor.java
// Using an ExecutorService to execute Runnables.
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;

public class TaskExecutor
{
public static void main(String[] args)
{
// create and name each runnable
PrintTask task1 = new PrintTask("task1");
PrintTask task2 = new PrintTask("task2");
PrintTask task3 = new PrintTask("task3");

System.out.println("Starting Executor");

// create ExecutorService to manage threads
ExecutorService executorService = Executors.newCachedThreadPool();

// start the three PrintTasks
executorService.execute(task1); // start task 1
executorService.execute(task2); // start task 2
executorService.execute(task3); // start task 3

// shut down ExecutorService--it decide when to shut down threads
executorService.shutdown();

System.out.printf("Tasks started, main ends.%n");
}
} // end class TaskExecutor

Fig 23.4 | Using an ExecutirService to execute Runnables.

Starting Executor
Tasks started, main ends

task1 going to sleep for 4806 milliseconds
task2 going to sleep for 2533 milliseconds
task3 going to sleep for 1132 milliseconds
task3 done sleeping
task2 done sleeping
task1 done sleeping
Starting Executor
Tasks started, main ends

task1 going to sleep for 3161 milliseconds
task2 going to sleep for 532m illiseconds
task3 going to sleep for 3440 milliseconds
task3 done sleeping
task1 done sleeping
task2 done sleeping

Fig.23.5 | Class that manages an integer array to be shared by multiple threads.

// construct a SimpleArray of a given size
public SimpleArray(int size)
{
array = new int[size];
}

// add a value to the shared array
public void add(int value)
{
int position = writeIndex; // store the write index

try
{
// put thread to sleep for 0-499 milliseconds
Thread.sleep(generator.nextInt(500));
}
catch(InterruptedException ex)
{
Thread.currentThread().interrupt(); // re-interrupt the thread
}

// put value in the appropriate element
array[position] = value;
System.out.printf("%s wrote %d to element %d.%n",
Thread.currentThread().getName(), value, position);

++writeIndex; // increment index of element to be written next
System.out.printf("Next write index: %d%n", writeIndex);
}

// used for outputting the contents of the shared integer array
public String toString()
{
return Arrays.toString(array);
}
} // end class SimpleArray
// Fig. 23.6: ArrayWriter.java
// Adds integers to an array shared with other Runnables
import java.lang.Runnable;

public class ArrayWriter implements Runnable
{
private final SimpleArray sharedSimpleArray;
private final int startValue;

public ArrayWriter(int value, SimpleArray array)
{
startValue = value;
sharedSimpleArray = array;
}

public void run()
{
for(int i = startValue; i < startValue + 3; i++)
{
sharedSimpleArray.add(i); // add an element to the shared array
}
}
} // end class ArrayWriter

Fig. 23.7 | Executing two Runnables to add elements to a shared array.

import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;

public class SharedArrayTest
{
public static void main(String[] arg)
{
// construct the shared object
SimpleArray sharedSimpleArray = new SimpleArray(6);

// create two tasks to write to the shared SimpleArray
ArrayWriter writer1 = new ArrayWriter(1, sharedSimpleArray);
ArrayWriter writer2 = new ArrayWriter(11, shareSimpleArray);

// execute the tasks with an ExecutorService
ExecutorService executorService = Executors.newCachedThreadPool();
executorService.execute(writer1);
executorService.execute(writer2);
executorService.shutdown();

try
{
// write 1 minute for both writers to finish executing
boolean tasksEnded = executorService.awaitTermination(1, TimeUnit.MINUTES);

if(tasksEnded)
{
System.out.printf("%nContents of SimpleArray:%n");
System.out.println(sharedSimpleArray); // print contents
}
else
System.out.println("Timed out while waiting for tasks to finish.");
}
catch(InterruptedException ex)
{
ex.printStackTrace();
}
} // end main
// end class SharedArrayTest
Academic Honesty!
It is not our intention to break the school's academic policy. Posted solutions are meant to be used as a reference and should not be submitted as is. We are not held liable for any misuse of the solutions. Please see the frequently asked questions page for further questions and inquiries.
Kindly complete the form. Please provide a valid email address and we will get back to you within 24 hours. Payment is through PayPal, Buy me a Coffee or Cryptocurrency. We are a nonprofit organization however we need funds to keep this organization operating and to be able to complete our research and development projects.