In: Computer Science
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");
}
}
}
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