Please write Java Multithreading Racers in one class : Your task in this assignm
ID: 3850004 • Letter: P
Question
Please write Java Multithreading Racers in one class : Your task in this assignment is to create a threaded class that "races" by counting and displaying the numbers from 1 to 10000. Each of the instances of this thread class should have a unique ID (i.e. the first instance should be numbered "1", the next instance should be numbered "2", etc.). Now that you have your threaded class, write a main/driver class that instantiates/spawns 10 instances of your threaded class and runs each of them. When the first thread completes and returns, invoke System.exit() to terminate the program; in so doing, you will be able to determine which thread "won" and achieved it's conclusion first. again please only one class and as simple as possible.
Explanation / Answer
Racers.java
class DemoThread implements Runnable{
@Override
public void run() {
int i;
for( i=1;i<=10000;i++)
{
Thread t=Thread.currentThread();
System.out.println(t.getName()+" " + i);
}
if(i==10000)
{
System.exit(0);
}
}
}
public class Racers {
public static void main(String[] args) {
// TODO Auto-generated method stub
DemoThread d1=new DemoThread();
DemoThread d2=new DemoThread();
DemoThread d3=new DemoThread();
DemoThread d4=new DemoThread();
DemoThread d5=new DemoThread();
DemoThread d6=new DemoThread();
DemoThread d7=new DemoThread();
DemoThread d8=new DemoThread();
DemoThread d9=new DemoThread();
DemoThread d10=new DemoThread();
Thread t1=new Thread(d1);
Thread t2=new Thread(d1);
Thread t3=new Thread(d1);
Thread t4=new Thread(d1);
Thread t5=new Thread(d1);
Thread t6=new Thread(d1);
Thread t7=new Thread(d1);
Thread t8=new Thread(d1);
Thread t9=new Thread(d1);
Thread t10=new Thread(d1);
t1.setName("1");
t2.setName("2");
t3.setName("3");
t4.setName("4");
t5.setName("5");
t6.setName("6");
t7.setName("7");
t8.setName("8");
t9.setName("9");
t10.setName("10");
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
t6.start();
t7.start();
t8.start();
t9.start();
t10.start();
}
}