Your task in this assignment is to create a threaded class that "races" by counting and displaying the numbers from 1 to 10. 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.
JAVA PROGRAM :
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class MyThread extends Thread{
MyThread(String name){
super(name);
}
@Override
public void run(){
for(int i=1;i<=10;i++){
System.out.println(i+" "+getName());
}
System.exit(0);
}
}
class Ideone
{
public static void main (String[] args) throws
java.lang.Exception
{
// Initializing threads
MyThread threads[] = new
MyThread[10];
for(int i=0;i<10;i++){
threads[i] = new
MyThread("Thread : "+Integer.toString(i));
}
//Invoking threads
for(int i=0;i<10;i++){
threads[i].start();
}
}
}
OUTPUT :
D:\>java Ideone
Thread : 1 - 1
Thread : 1 - 2
Thread : 1 - 3
Thread : 1 - 4
Thread : 1 - 5
Thread : 1 - 6
Thread : 9 - 1
Thread : 9 - 2
Thread : 3 - 1
Thread : 3 - 2
Thread : 3 - 3
Thread : 3 - 4
Thread : 3 - 5
Thread : 3 - 6
Thread : 3 - 7
Thread : 3 - 8
Thread : 3 - 9
Thread : 2 - 1
Thread : 3 - 10
Thread : 9 - 3
Thread : 10 - 1
Thread : 1 - 7
Get Answers For Free
Most questions answered within 1 hours.