Question

Need some help on the following JAVA problem: Write a program in which the main thread...

Need some help on the following JAVA problem:

Write a program in which the main thread creates two threads named “Display” and “Daemon”. The first thread (Display) executes in an infinite loop and prints out its name and system time every 1 second until it is interrupted by the main thread. The second thread is a daemon thread that executes in an infinite loop and prints out its name. The main thread waits for a specific number of seconds n before interrupting thread Display. The value n should be read in from the keyboard using command-line arguments.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Here is the completed code for this problem. Explanation of the code is given in java comments, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks

// Threads.java

import java.util.Calendar;

public class Threads {

    // a flag indicating if the main thread wants to interrup display thread

    static boolean done = false;

    // declaring two Thread objects

    static Thread display = null, daemon = null;

    public static void main(String[] args) throws InterruptedException {

         // if no command line arguments provided, displaying usage and quitting

         if (args.length == 0) {

             System.out

                      .println("Specify value for 'n' while running the program");

             System.out.println("Usage: java Threads <n>");

             System.exit(0);

         }

         // otherwise parsing first argument as integer n

         int n = Integer.parseInt(args[0]);

         // initializing display thread

         display = new Thread(new Runnable() {

             @Override

             public void run() {

                 // looping until done is true

                 while (!done) {

                      // displaying thread name and current date and time, if you

                      // prefer to display milliseconds elapsed since epoch, you

                      // may use System.currentTimeMillis() instead.

                      System.out.println(display.getName() + ": "

                               + Calendar.getInstance().getTime());

                      // pausing for 1000 ms or 1 second

                      try {

                          Thread.sleep(1000);

                      } catch (InterruptedException e) {

                      }

                 }

                 // alerting user that display thread is exiting

                 System.out.println("Display thread is exiting.");

             }

         });

         // setting name for display thread

         display.setName("Display");

         // initializing daemon thread

         daemon = new Thread(new Runnable() {

             @Override

             public void run() {

                 // looping indefinitely

                 while (true) {

                      // displaying thread's name

                      System.out.println(daemon.getName());

                      // pausing for 100 ms or 1/10th of a second

                      try {

                          Thread.sleep(100);

                      } catch (InterruptedException e) {

                      }

                 }

             }

         });

         // setting daemon name

         daemon.setName("Daemon");

         // making daemon an actual Daemon thread, which means the thread will

         // run on background independent on other threads, and the system will

         // terminate this thread only if it is the only thread left which is

         // running

         daemon.setDaemon(true);

         // starting both threads

         display.start();

         daemon.start();

         // pausing main thread for n seconds

         Thread.sleep(n * 1000);

         // setting done to true, which will cause the display thread to stop,

         // which make daemon thread the only one left, so the program will

         // finally terminate daemon thread also. if we dont make the second

         // thread a 'daemon', it will loop forever until we manually terminate

         // the program.

         done = true;

    }

}

/*OUTPUT (when n=4 (i.e ran with command: java Threads 4 ))*/

Daemon

Display: Sat Feb 08 10:45:43 IST 2020

Daemon

Daemon

Daemon

Daemon

Daemon

Daemon

Daemon

Daemon

Daemon

Daemon

Display: Sat Feb 08 10:45:44 IST 2020

Daemon

Daemon

Daemon

Daemon

Daemon

Daemon

Daemon

Daemon

Daemon

Daemon

Display: Sat Feb 08 10:45:45 IST 2020

Daemon

Daemon

Daemon

Daemon

Daemon

Daemon

Daemon

Daemon

Daemon

Daemon

Display: Sat Feb 08 10:45:46 IST 2020

Daemon

Daemon

Daemon

Daemon

Daemon

Daemon

Daemon

Daemon

Daemon

Daemon

Display thread is exiting.

Add a comment
Know the answer?
Add Answer to:
Need some help on the following JAVA problem: Write a program in which the main thread...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • JAVA Program! Write a program that makes use of threading. You will have one thread count how many times a second has p...

    JAVA Program! Write a program that makes use of threading. You will have one thread count how many times a second has passed and the second thread will count how many times 3 seconds has passed This will occur in an infinite loop and the counts will be printed to the screen. Indent the count of one of the threads for easier viewing Write a program that makes use of threading. You will have one thread count how many times...

  • kindly make a java threaded program main class will accept n number and produce user inputed...

    kindly make a java threaded program main class will accept n number and produce user inputed array of n elements make 3 child threads(class) out of one main thread(class) must use thread.sleep and thread synchronization one thread create max of array elements one will min of array elements one will provide average of array elements then display of array will occur

  • Write a C program for Linux called pipes.c that does the following: In the main() function,...

    Write a C program for Linux called pipes.c that does the following: In the main() function, it creates a pipe using the pipe() function, then creates two child processes with fork(). Child 1 redirects stdout to the write end of the pipe and then executes with execlp() the "ps -aux" command. Child 2 redirects its input from stdin to the read end of the pipe, then it executes the "sort -r -n -k 5" command. After creating both children, the...

  • I need to creatre a C++ program that can modify the producer and consumer. My main...

    I need to creatre a C++ program that can modify the producer and consumer. My main programmig language is C++. Modify "Producer and Consumer Problem" from lecture note so that it can use all buffer space, not "buffersize – 1" as in the lecture note. This program should work as follows: 1. The user will run the program and will enter two numbers on the command line. Those numbers will be used for buffersize and counter limit. 2. The main...

  • Please help me to solve this problem with java language! write a program that runs a...

    Please help me to solve this problem with java language! write a program that runs a thread which prints a timestamp and then waits a second by doing the following: 1. Implement a class that implements the Runnable interface. (1 point) 2. Place the code for your task into the run method of your class. (6 points) a) To get the date and time, construct a Date object. b) To wait a second, use the sleep method of the Thread...

  • JAVA PROGRAM. I need to write a program in java that will perform matrix addition and both matric...

    JAVA PROGRAM. I need to write a program in java that will perform matrix addition and both matrices have N rows and M columns, N>1 and M>1. The two matrices must be divided to four equal size sub-matrices and each sub-matrix has dimensions N/2 X M/2. I need to create four threads and each thread performs a sub-set of addition on one pair of the sub-matrices. I also need an extra thread for networking. The network part of this uses...

  • This Java program reads an integer from a keyboard and prints it out with other comments....

    This Java program reads an integer from a keyboard and prints it out with other comments. Modify the comments at the top of the program to reflect your personal information. Submit Assignment1.java for Assignment #1 using Gradescope->Assignemnt1 on canvas.asu.edu site. You will see that the program has a problem with our submission. Your program is tested with 4 testcases (4 sets of input and output files). In order to pass all test cases, your program needs to produce the same...

  • Sorting Threads Assignment Overview Write a multithreaded sorting program in Java which uses the ...

    Sorting Threads Assignment Overview Write a multithreaded sorting program in Java which uses the merge sort algorithm. The basic steps of merge sort are: 1) divide a collection of items into two lists of equal size, 2) use merge sort to separately sort each of the two lists, and 3) combine the two sorted lists into one sorted list. Of course, if the collection of items is just asingle item then merge sort doesn’t need to perform the three steps,...

  • Write a complete Java program, including comments in both the main program and in each method,...

    Write a complete Java program, including comments in both the main program and in each method, which will do the following: 0. The main program starts by calling a method named introduction which prints out a description of what the program will do. This method is called just once.      This method is not sent any parameters, and it does not return a value. The method should print your name. Then it prints several lines of output explaining what the...

  • Creating a Shell Interface Using Java This project consists of modifying a Java program so that...

    Creating a Shell Interface Using Java This project consists of modifying a Java program so that it serves as a shell interface that accepts user commands and then executes each command in a separate process external to the Java virtual machine. Overview A shell interface provides the user with a prompt, after which the user enters the next command. The example below illustrates the prompt jsh> and the user’s next command: cat Prog.java. This command displays the file Prog.java on...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT