JAVA Programming: Simulate 10 runners (threads), these runners sleep a random am
ID: 3691704 • Letter: J
Question
JAVA Programming:
Simulate 10 runners (threads), these runners sleep a random amount of time drawn from numbers between 500ms - 1000ms, upon waking up runners run a random distance between 5 - 10 mtrs and then go back to sleep by choosing a random sleeping intervals, (a number between 500ms - 1000ms). The one finishes 100 mtrs first is the winner. In our output you should show how much they run whenever they wakeup and rank them based on shortest time to 100 mtrs upon all the runners complete the race.
Explanation / Answer
/*two documents*/
/**************************************************************
first; the class runner
**************************************************************/
package runners;
/**
* Auto Generated Java Class.
*/
public class Runner extends java.lang.Thread {
public Runner (String msg)
{
super(msg);
}
public void run ()
{
long initialTime = System.currentTimeMillis();
for(int i=0; i<=100;){
try{
sleep(((int)(Math.random()*501 + 500)));
}catch(InterruptedException ex){}
int j=((int)(Math.random()*6 + 5));
i=i+j;
System.out.println(i);
System.out.println(this.getName());
}
System.out.println("the " + this.getName() + " has finish the run on time "
+ (System.currentTimeMillis()- initialTime )
+ " milisec");
}
}
/***************************************
second the main
*******************************************/
package runners;
public class Main {
public static void main (String[] args) {
Thread runner1 =new Runner("runner 1");
Thread runner2 =new Runner("runner 2");
Thread runner3 =new Runner("runner 3");
Thread runner4 =new Runner("runner 4");
Thread runner5 =new Runner("runner 5");
Thread runner6 =new Runner("runner 6");
Thread runner7 =new Runner("runner 7");
Thread runner8 =new Runner("runner 8");
Thread runner9 =new Runner("runner 9");
Thread runner10 =new Runner("runner 10");
long initialTime = System.currentTimeMillis();
runner1.start();
runner2.start();
runner3.start();
runner4.start();
runner5.start();
runner6.start();
runner7.start();
runner8.start();
runner9.start();
runner10.start();
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.