Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

JAVA Given below is the code of a program that uses four threads to shuffle the elements in an array. The code for the thread

JAVA
Given below is the code of a program that uses four threads to shuffle the elements in an array. The code for the thread Shuffler is also given. Critically analyse the performance of this program and re-write it so that it optimizes the performance of the threads and does not deadlock.
public class ArrayShufflerTest{
public static void main(String[] args) {
in data[] = new int[1000];
for(int j = 0; j
Object lock= new Object();
Thread t1 = new Shuffler(data,lock,100);
Thread t2 = new Shuffler(data,lock,100);
Thread t3 = new Shuffler(data,lock,100);
Thread t4 = new Shuffler(data,lock,100);
t1.start(); t2.start;() t3.start(); t4.start();
try{t1.join(); t2.join(); t3.join(); t4.join();}
catch(InterruptedException e){}
for(int j = 0; j
System.out.printf("%2d", data[j];
System.out.println();
}
}
class Shuffler extends Thread{
int data[]; int shuffles;
Object lock;
public Shuffler(int d[], Object lk, int sh){
data = d; shuffles= sh; lock = lk;
}
public void run(){
int k = 0;
while(k
//select two random index values and exchange data
int left= (int)(Math.random()*data.length);
int right= (int)(Math.random()*data.length);
synchronized(lock){
int temp = data[left]; data[left] = data[right];
data[right] = temp;
}
k++;
}
}
}

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Fundamentals Of Database Management Systems

Authors: Mark L. Gillenson

2nd Edition

0470624701, 978-0470624708

More Books

Students also viewed these Databases questions

Question

How many Tables Will Base HCMSs typically have? Why?

Answered: 1 week ago

Question

What is the process of normalization?

Answered: 1 week ago