Please help: Analyze and Modify a Java program using the extends and runnable methods. You will be creating your own threaded program using the threadExtend.java
Please help: Analyze and Modify a Java program using the “extends” and “runnable” methods. You will be creating your own threaded program using the threadExtend.java code and the threadRunnable.java code.
A.) Focus the threadExtend.java code
DETAILS TO NOTE:
- It creates 4 instances of the same thread. This means that the thread code is actually running 4 separate times
- The thread accepts 2 parameters, an INTEGER from 1 to 4, as well as an ID
- Note the parameters are hard coded as the threads are created
- The thread prints a message every 250 ms (4 times per second)
- Note that each time a thread (1, 2, 3 or 4) prints, it is ABOUT 250ms from the last time it printed
I.) Describe how this is happening: Notice that during a single loop, some threads are VERY CLOSE together in time in milliseconds... this means they are running almost simultaneously
II.) What happened to the second thread before the program exited?
III.) Describe how might threads be useful and how would you use them?... (Note: they are background processes thbat run as the main code keeps running and can pass data back to the main code when needed or requested).
IV.) ADD a 5th thread instance passing in a unique ID (5 should be the thread number passed in) MODIFY the and COMMENT the thread code to know when it is executing your thread, and print a statement with the name Bob in it, for example:
"This is Bob's thread... ID'" + yourIDnumber
B.) Edit the threadRunnable.java code
I.) Get start time in nanoseconds of the thread
II.) Execute a loop 5000 times to (ignore the 'switch' in the comment... you just need a loop)
a.) Multiply 2 numbers (hard code them if you want)
b.) Divide 2 numbers (hard code them if you want)
c.) Take the square root of a number (hard code it if you want)
III.) Get the end time in nanoseconds
IV.) PRINT the time taken for the 50000 iteration loop
The code for the nanosecond time calculation is here:
//at the top or the run code, declare variables
long startns;
long endns;
long diffns;
//if you know this is your thread:
//get start time of loop in nanoseconds
startns =System.nanoTime();
//loop 50000 times and do some math
for (int idx=0; idx< 50000 ; ++idx)
{
//do some calculations... add, multiply, subtract
}
//loop complete, get end time
endns = System.nanoTime();
//calculate time in ns of loop by subtracting start from end time
diffns = endns-startns;
// print out how long it took
System.out.println(this.threadNumber + ": My Thread math loop took: " + diffns + " nanoseconds");
_______________________________________________________________
Below is the code for "threadExtend.java"
package com.java24hours;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
class WorkerThread extends Thread {
int threadId; //unique ID passed in by each thread started by the main code
int threadNumber; // order of threads created
//create a variable to hold the current date/time for display in the thread
// show MILLISECONDS
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
//thread contructor to accept input ID
WorkerThread(int threadId, int threadNumber)
{
this.threadId = threadId;
this.threadNumber = threadNumber;
}
@Override
public void run() {
//show each thread unique execution
/** NOTE the threads are running as simultaneously as possible
* see the thread NUMBER and TIME in milliseconds...
* each thread is running 5 loops and sleeping for 250 milliseconds
* that is 4 times per second, so for 4 loops, each thread should take 1 second
*/
for(int i=0; i < 4; i++) {
//UPDATE the time in every loop
Date currentdate = new Date();
System.out.print(this.threadNumber + ": thread in loop" + i + " of thread with ID: " + this.threadId + "");
String stringDate = sdf.format(currentdate);
System.out.println(" Time of execution: " + stringDate);
// Sleep for 1/4 second (sleep is in ms)
//break up the output
if (this.threadNumber == 4)
System.out.println("");
try {
Thread.sleep(250); //each loop should be about 250ms apart
} catch (InterruptedException e) {
// Worker class has an interrupt() method because it inherits from Thread
//could be used to stop a thread on an alarm from the main code
System.out.println("Interupt caught in thread: "+ this.threadId + " " + e.getMessage() + "");
break;
}
}
}
}
public class threadExtend {
public static void main(String[] args)
{
//create 2 working threads with unique IDs
WorkerThread worker1 = new WorkerThread(135,1);
worker1.start();
try {
//delay 10 ms before starting second thread
Thread.sleep(10);
} catch (InterruptedException ex) {
Logger.getLogger(threadExtend.class.getName()).log(Level.SEVERE, null, ex);
}
WorkerThread worker2 = new WorkerThread(246,2);
worker2.start();
try {
//delay 10 ms before starting second thread
Thread.sleep(10);
} catch (InterruptedException ex) {
Logger.getLogger(threadExtend.class.getName()).log(Level.SEVERE, null, ex);
}
WorkerThread worker3 = new WorkerThread(790,3);
worker3.start();
try {
//delay 10 ms before starting second thread
Thread.sleep(10);
} catch (InterruptedException ex) {
Logger.getLogger(threadExtend.class.getName()).log(Level.SEVERE, null, ex);
}
WorkerThread worker4 = new WorkerThread(802,4);
worker4.start();
// You can call interrupt() to cause an exception in a thread
// The thread code needs to handle interrupts.
//maybe there was an alarm in the main code that some data feeding worker1 is bad
try
{
Thread.sleep(500); //thread 2 will be interrputed in 1/2 second
worker2.interrupt();
Thread.sleep(1000); //all threads should complete by the time this sleep is over
}
catch (Exception ex)
{
System.out.println("Main Thread Sleep Exception");
}
}
}
_______________________________________________________________
Below is the code for "threadRunnable.java"
package com.java24hours;
import java.util.logging.Level;
import java.util.logging.Logger;
class WorkerThreadR implements Runnable {
int threadId; //unique ID passed in by each thread started by the main code
//thread contructor to accept input ID
WorkerThreadR(int threadId)
{
this.threadId = threadId;
}
@Override
public void run() {
//show exch thread unique execution
for(int i=0; i<10; i++) {
System.out.println("'implements' thread in loop" + i + " of thread: " + this.threadId);
// Sleep for 1/4 second (sleep is in ms)
try {
Thread.sleep(250);
} catch (InterruptedException e) {
// Worker class has an interrupt() method because it inherits from Thread
//could be used to stop a thread on an alarm from the main code
System.out.println("Interupt caught in thread: "+ this.threadId + " " + e.getMessage());
break;
}
}
}
}
public class threadRunnable {
public static void main(String[] args)
{
//create 2 working threads with unique IDs
// this type of thread requires the constructor to be instantiated
// then passed to the thread
WorkerThreadR worker1 = new WorkerThreadR(135);
Thread threadw1 = new Thread(worker1);
threadw1.start();
try {
//delay 10 ms before starting second thread
Thread.sleep(10);
} catch (InterruptedException ex) {
Logger.getLogger(threadExtend.class.getName()).log(Level.SEVERE, null, ex);
}
WorkerThreadR worker2 = new WorkerThreadR(246);
Thread threadw2 = new Thread(worker2);
threadw2.start();
// You can call interrupt() to cause an exception in a thread
// The thread code needs to handle interrupts.
//maybe there was an alarm in the main code that some data feeding worker1 is bad
try
{
Thread.sleep(1000); //thread 1 will be interrputed in 1 second
threadw1.interrupt();
}
catch (Exception ex)
{
System.out.println("Main Thread Sleep Exception");
}
}
}
Step by Step Solution
3.45 Rating (158 Votes )
There are 3 Steps involved in it
Step: 1
SOLUTION Explaination thread ExtendJava 1Describe how this is happening Notice that during a single loop some threads are VERY CLOSE together in time in milliseconds this means they are running almost ...See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started