Question

In: Computer Science

4.) Create a Java program using the “extends” and “runnable” methods. You will be creating your...

4.) Create 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 + "\n");
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("\nInterupt caught in thread: "+ this.threadId + " " + e.getMessage() + "\n");
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");
}
}
  
}

Solutions

Expert Solution

ANS ->

Explaination "threadExtend.java" :

1)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

-->

A) "WorkeThread.java" is user defined class. it must be extended from java.lang.Thread class

B)The user defined class must be declared with run method which is overriding method of thread class.Required logic is coded with in run method

C)Create object for user defined class.so WorkeThread.java creating 5 object in extendsThread.java

WorkThread worker1 = new WorkThread(135,1);

WorkThread worker2 = new WorkThread(246,2);

WorkThread worker3 = new WorkThread(790,3);

WorkThread worker4 = new WorkThread(802,4);

D)Execute run() method using start() method

objecect ref.start();

whenever we used  objecect ref.start() the thread is registered within the thread shedular ,creates seprate thread stack and load the run() method with business logic onto thread stack.

`II.) What happened to the second thread before the program exited?

->In multithreading process multiple thread stacks are created and all the thread stack are executed simultaneously.

so second thread time slice is finished and it shows Interupt caught in thread: 246 sleep interrupted

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).

->

To complete batch processing quickly we can implement paralell processing using Multi Threading.To work with Multi Threading we can use Executor Services in java

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

---->i am taken DemoThread.java iinstead of extendsThread.java

package com.nacre.oop;

import java.util.logging.Level;
import java.util.logging.Logger;

public class DemoThread extends Thread {

   public static void main(String[] args) {
  
      
       //create 2 working threads with unique IDs
      

       WorkThread worker1 = new WorkThread(135,1);
      
       System.out.println("****thread 1****");
       worker1.start();
      
       try {
       //delay 10 ms before starting second thread
       Thread.sleep(10);
       } catch (InterruptedException ex) {
       Logger.getLogger(DemoThread.class.getName()).log(Level.SEVERE, null, ex);
       }
       WorkThread worker2 = new WorkThread(246,2);
       System.out.println("******Thread 2*****");
       worker2.start();
      
       try {
       //delay 10 ms before starting second thread
       Thread.sleep(10);
       } catch (InterruptedException ex) {
           System.out.println("*******Second thread******");
       Logger.getLogger(DemoThread.class.getName()).log(Level.SEVERE, null, ex);
       }
       WorkThread worker3 = new WorkThread(790,3);
       System.out.println("****Thread 3***");
       worker3.start();
      
       try {
       //delay 10 ms before starting second thread
       Thread.sleep(10);
       } catch (InterruptedException ex) {
       Logger.getLogger(DemoThread.class.getName()).log(Level.SEVERE, null, ex);
       }
       WorkThread worker4 = new WorkThread(802,4);
       System.out.println("******Thread 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");
       }
      
       //5th Thread
       WorkThread worker5 = new WorkThread(1000,5);
       worker5.start();
   }
      
   }

*****WorkThread.java***

package com.nacre.oop;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class WorkThread 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
   public WorkThread(int threadId, int threadNumber) {
       super();
       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 + "\n");
   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 == 5)
   System.out.println("This is the bob thread id :"+threadNumber);
  
   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("\nInterupt caught in thread: "+ this.threadId + " " + e.getMessage() + "\n");
   break;
   }
   }
   }

  
  

}

*****output********

****thread 1****
1: thread in loop0 of thread with ID: 135
Time of execution: 2020-10-31 09:27:05.414
******Thread 2*****
2: thread in loop0 of thread with ID: 246
Time of execution: 2020-10-31 09:27:05.437
****Thread 3***
3: thread in loop0 of thread with ID: 790
Time of execution: 2020-10-31 09:27:05.453
******Thread 4********
4: thread in loop0 of thread with ID: 802
Time of execution: 2020-10-31 09:27:05.463
1: thread in loop1 of thread with ID: 135
Time of execution: 2020-10-31 09:27:05.681
2: thread in loop1 of thread with ID: 246
Time of execution: 2020-10-31 09:27:05.696
3: thread in loop1 of thread with ID: 790
Time of execution: 2020-10-31 09:27:05.706
4: thread in loop1 of thread with ID: 802
Time of execution: 2020-10-31 09:27:05.730
1: thread in loop2 of thread with ID: 135
Time of execution: 2020-10-31 09:27:05.934
2: thread in loop2 of thread with ID: 246
Time of execution: 2020-10-31 09:27:05.950
3: thread in loop2 of thread with ID: 790

Interupt caught in thread: 246 sleep interrupted

Time of execution: 2020-10-31 09:27:05.966
4: thread in loop2 of thread with ID: 802
Time of execution: 2020-10-31 09:27:05.997
1: thread in loop3 of thread with ID: 135
Time of execution: 2020-10-31 09:27:06.197
3: thread in loop3 of thread with ID: 790
Time of execution: 2020-10-31 09:27:06.220
4: thread in loop3 of thread with ID: 802
Time of execution: 2020-10-31 09:27:06.251
5: thread in loop0 of thread with ID: 1000
Time of execution: 2020-10-31 09:27:06.969
This is the bob thread id5
5: thread in loop1 of thread with ID: 1000
Time of execution: 2020-10-31 09:27:07.222
This is the bob thread id5
5: thread in loop2 of thread with ID: 1000
Time of execution: 2020-10-31 09:27:07.485
This is the bob thread id5
5: thread in loop3 of thread with ID: 1000
Time of execution: 2020-10-31 09:27:07.739
This is the bob thread id5


Related Solutions

COP 2800, Java Programming Assignment 6-1 Using Java create a program using the “Methods” we covered...
COP 2800, Java Programming Assignment 6-1 Using Java create a program using the “Methods” we covered this week. come up with a “problem scenario” for which you can create a “solution”. Utilize any/all of the examples from the book and class that we discussed. Your program should be interactive and you should give a detailed statement about what the “description of the program – purpose and how to use it”. You should also use a “good bye” message. Remember to...
Create a project plan on the game or application you are creating. Using java programming. The...
Create a project plan on the game or application you are creating. Using java programming. The project plan should include the following: A description of the game or application The IDE or game engine your plan to use to create the game or app and information on how you are going to develop the game or app If you choose to create a game, how are you going to approach the game design and game development process or if you...
8) Create the following program using Java. Circle calculation using methods Create scanner declare double variable...
8) Create the following program using Java. Circle calculation using methods Create scanner declare double variable radius = -999 declare character choice create do while loop inside of do loop write: System.out.println(); System.out.println("*** CIRCLE CALCULATIONS ***"); System.out.println(); System.out.println("1. Enter the radius of the circle"); System.out.println("2. Display the area of the circle"); System.out.println("3. Display the circumference of the circle"); System.out.println("4. Quit"); System.out.println(); System.out.println("Enter a number from 1 - 4"); System.out.println(); Declare choice character and relate to scanner declare switch (choice) case...
Using java you have to create a simple program that will allow for the storage of...
Using java you have to create a simple program that will allow for the storage of requests for money. Each request will consist of a person's name and dollar amount (US dollars). The business rules are straight forward. Each name should be a first and last name. The first letter of each element in the name should be capitalized. The dollar amount should be between 1 and 1000 dollars and include cents (2 decimals). You should include validations, but it...
In java Create a class named CellPhoneCase that extends your Case class – it inherits all...
In java Create a class named CellPhoneCase that extends your Case class – it inherits all the fields and methods from the Case class. It should also contain:  One field for a CellPhone object. Be sure to put in the appropriate access modifier. (private, public)  A constructor with 3 parameters – owner’s name, Case color, the phone number of the cell phone that will be in the Case. This constructor MUST call the super class’s constructor. Then set...
3) Create a Java program that uses NO methods, but use scanner: Write a program where...
3) Create a Java program that uses NO methods, but use scanner: Write a program where you will enter the flying distance from one continent to another, you will take the plane in one country, then you will enter miles per gallon and price of gallon and in the end it will calculate how much gas was spend for that distance in miles. Steps: 1) Prompt user to enter the name of country that you are 2) Declare variable to...
how to create BANKACCOUNT program using Arrays in JAVA.
how to create BANKACCOUNT program using Arrays in JAVA.
java program that coverts base13 to decimal. without using array and methods.
java program that coverts base13 to decimal. without using array and methods.
java program Create a program that creates and prints a random phone number using the following...
java program Create a program that creates and prints a random phone number using the following format: XXX-XXX-XXXX. Make sure your output include the dashes.  Do not let the first three digits contain an 8 or 9 (HINT: do not be more restrictive than that) and make sure that the second set of three digits is not greater than 773. Helpful Hint:   Think though the easiest way to construct the phone number. Each digit does do not have to be determined...
Use JAVA language. Using the switch method concept create a program in which you have an...
Use JAVA language. Using the switch method concept create a program in which you have an artist (singer) and the list of his or her songs. Add 18 songs. Then alter the script to achieve the following in each test run: a) Print all the songs. b) Print only song 15. c) Print only song 19.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT