Please code using Java and show an example that it will run successfully in an J
ID: 3679511 • Letter: P
Question
Please code using Java and show an example that it will run successfully in an JAVA IDE. Code the following:
Please code both programs, one WITH synchronization and one WITHOUT synchronization. Also please Define the Integer wrapper obect as stated in the instructions below.
0.4 Synchronize threads) Write a program that launches 1,000 threads. Each thread adds 1 to a variable sum that initially is 0. Define an Integer wrapper object to hold sum. Run the program with and without synchronization to see its effect.Explanation / Answer
//importing packages
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
class MutableInteger {
private int i;
//default constructor that sets the value to 0
public MutableInteger() {
this(0);
}
//constructor to pass and user defined value
public MutableInteger(int i) {
this.i= i;
}
//define inc function for incrementing I value
public int inc() {
return ++i;
}
//define syncinc function for syncnronized incrementing I value
public synchronized int syncInc() {
return ++i;
}
}
//with out synchronization
public class mythread{
//declaring variables as static
private static int countthread;
public static void main(String[] args){
/* Get an executor service that will run a maximum of 100 threads at a time: */
ExecutorService exec = Executors.newFixedThreadPool(100);
for ( countthread = 0; countthread <= 100; countthread++)
{
/* execute the task to run concurrently as a runnable: */
exec.execute(new sum());
}
exec.shutdown();
try {
/* The tasks are now running concurrently.wait until all work is done,
with a timeout of 50 seconds: */
boolean b = exec.awaitTermination(50, TimeUnit.SECONDS);
System.out.println("All done: " + b);
} catch (InterruptedException e) { e.printStackTrace(); }}
}
//with synchronization
class sum extends Thread {
private MutableInteger sum = new MutableInteger();
public void run() {
/* do the work to be done in its own thread */
System.out.println("at " + Thread.currentThread()+"sum is "+sum.syncInc());
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.