Using NetBeans. Create a threaded class that \"races\" by counting and displayin
ID: 3864208 • Letter: U
Question
Using NetBeans. 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.
Explanation / Answer
Steps:
* @author MONALI
*/
public class Thread1 {// CREATE NORMAL CLASS TO COUNT AND DISPLAY 10 NUMBERS 0 TO 9
public void display(){
for(int i =0;i<10;i++){
System.out.println( "Instances of I:" +i);
}
System.exit(0);
}
}
NOW CREATE MAIN THREAD CLASS:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author MONALI
*/
public class MainTest extends Thread{
public static void main(String[] args) throws InterruptedException{
Thread[] threads= new Thread[10]; //IT INSTANIATES OR SPAWNS 10 INSTANCES OF YOUR THREAD CLASS
for(int i=0;i<10;i++){
threads[i] = new Thread(new Runnable(){
public void run(){
Thread1 run = new Thread1();
run.display();
}
});
System.out.println(threads[i].getName());// GETTING ALL THE 10 THREADS CREATED AND RUNNNG
threads[i].start();
}
for(int i = 0; i < 10; i++) {
threads[i].join();
}
}
OUTPUT:
Thread-0
Thread-1
Thread-2
Thread-3
Thread-4
Thread-5
Thread-6
Thread-7
Thread-8
Thread-9
Instances of I:0
Instances of I:1
Instances of I:2
Instances of I:3
Instances of I:4
Instances of I:5
Instances of I:6
Instances of I:7
Instances of I:8
Instances of 1:9
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.