Each uploader keeps uploading without stoping. Modify the given program to set t
ID: 3570934 • Letter: E
Question
Each uploader keeps uploading without stoping. Modify the given program to set the size of the file randomly between 500KB and 2MB, taking in consideration that the connection speed varies between 100KB to 200KB download, and 50KB to 80KB upload.
Ex:
import java.util.concurrent.Semaphore;
public class UploaderThreadSample extends Thread {
private static Semaphore semaphore;
private String name;
public UploaderThreadSample(String name) {
this.name = name;
}
// A constructor takes name parameter
public static void initialize() {
semaphore = new Semaphore(2);
}
@Override
public void run() {
while (true) {
try {
semaphore.acquire();
// Critical Section Starts
System.out.println(this.name + " {Uploading}");
// sleeping for two seconds
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
semaphore.release();
// Critical Section Ends
System.out.println(this.name + " {idle}");
}
try {
// sleeping for random period between 0 and 999 milliseconds
Thread.sleep((long) (Math.random() % 1000));
}
catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
UploaderThreadSample.initialize();
// creating 5 uploaders to work simultaneously
for (int i = 1; i <= 5; i++) {
UploaderThreadSample uploader = new UploaderThreadSample("U" + i);
uploader.start();
}
}
}
Explanation / Answer
import java.util.concurrent.Semaphore;
public class UploaderThreadSample extends Thread {
private static Semaphore semaphore;
private String name;
public UploaderThreadSample(String name) {
this.name = name;
}
// A constructor takes name parameter
public static void initialize() {
semaphore = new Semaphore(2);
}
@Override
public void run() {
while (true) {
try {
semaphore.acquire();
// Critical Section Starts
System.out.println(this.name + " {Uploading}");
// sleeping for two seconds
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
semaphore.release();
// Critical Section Ends
System.out.println(this.name + " {idle}");
}
try {
// sleeping for random period between 0 and 999 milliseconds
Thread.sleep((long) (Math.random() % 1000));
}
catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
UploaderThreadSample.initialize();
// creating 5 uploaders to work simultaneously
for (int i = 1; i <= 5; i++) {
UploaderThreadSample uploader = new UploaderThreadSample("U" + i);
uploader.start();
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.