1

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

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.

Answers

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.


Similar Solved Questions

1 answers
A 2000 [Ib) sports car collides into the rear end of a 5000 [ib] SUV stopped...
A 2000 [Ib) sports car collides into the rear end of a 5000 [ib] SUV stopped at a red light. The bumpers lock, the brakes are locked, and the two cars skid forward 15.0 [t] before stopping. The police officer, knowing that the coefficient of kinetic friction between tires and road is 0.85 calculates...
1 answers
What spiritual considerations surrounding a disaster can arise for individuals, communities, and health care providers? Explain...
What spiritual considerations surrounding a disaster can arise for individuals, communities, and health care providers? Explain your answer in the context of a natural or manmade disaster. How can a community health nurse assist in the spiritual care of the individual, community, self, and colleague...
1 answers
How do you solve #t^ { 2} - 51= 93#?
How do you solve #t^ { 2} - 51= 93#?...
1 answers
Should platforms like Facebook and Twitter actively remove posts that spread misinformation? How can we decipher...
Should platforms like Facebook and Twitter actively remove posts that spread misinformation? How can we decipher fake news from real news, especially in regard to things that could potentially harm us? Some ads are easy to tell that the claims are false just using the old adage "if it's too ...
1 answers
From the edge of a clif height h=20m, a ball is lunched with intial velocity v=5m/s...
From the edge of a clif height h=20m, a ball is lunched with intial velocity v=5m/s at angle of 30 degrees with the horizontal, ignore air friction assume g= 10m/s^2 A) write the horizontal and vertical position and velocity equation of motion B)Compute horizontal distance from the edge of the clif...
1 answers
Question 18 5 pts The original arc reactor designed by Tony Stark to power his Iron...
Question 18 5 pts The original arc reactor designed by Tony Stark to power his Iron Man suit was fueled by Pd-103, which is an isotope of palladium metal that decays by electron capture into stable Rh-103. The half-life of Pd-103 is 17 days. A new fuel cell for the arc reactor contains 1.6 grams of ...
1 answers
A client is to fake warfarin sodium (Coumadin) 5 mg p.o at home. Which should be...
A client is to fake warfarin sodium (Coumadin) 5 mg p.o at home. Which should be included in the client’s discharge instructions? a) tell your dentist that you are taking Coumadin b) treat headaches with aspirin rather than acetaminophen c) take the medication with meals d) eat a diet in green...
1 answers
For question 2, the initial amount of O2 is 2 and of CH4 is 1. This...
For question 2, the initial amount of O2 is 2 and of CH4 is 1. This what I believe it is honestly not completly sure due to the fac that this is all information I can. Please just try your best with the information adviliable. Question 1 An unknown chemical compound has the four elements with the fo...
1 answers
585/1000 Resources Hint Check Answer Calculate the pH for each case in the titration of 500...
585/1000 Resources Hint Check Answer Calculate the pH for each case in the titration of 500 ml. of 0.240 M HCO(a) with 0.240 M KOH(aq). Use the ionization constant for HCIO. What is the pll before addition of any KOH What is the pll after addition of 250 mL KOH? pH = What is the pH alter addition of...
1 answers
Can "love" be a noun, verb, adjective, and adverb?
Can "love" be a noun, verb, adjective, and adverb?...
1 answers
There is a boy with a mass of 55kg starting at rest going down a slide which is 4m high (y distance) and 6m (x distance) and his final velocity at the end is 4.5m/s then what is the average F of friction acting against him as he goes down the slide?
There is a boy with a mass of 55kg starting at rest going down a slide which is 4m high (y distance) and 6m (x distance) and his final velocity at the end is 4.5m/s then what is the average F of friction acting against him as he goes down the slide?...
1 answers
42. Sympathetic preganglionic axons A. can synapse in terminal ganglia. B. must synapse in parasympathetic ganglia....
42. Sympathetic preganglionic axons A. can synapse in terminal ganglia. B. must synapse in parasympathetic ganglia. C can synapse with cells in the adrenal cortex. D. can synapse in the dorsal root ganglion. E, can synapse in either chain or collateral ganglia. 43. The celiac, superior rnesentenc, a...
2 answers
Collison and Ryder Company (C&R) has been experiencing declining market conditions for its sportswear division. Management...
Collison and Ryder Company (C&R) has been experiencing declining market conditions for its sportswear division. Management decided to test the assets of the division for possible impairment. The test revealed the following: book value of division’s assets, $26.5 million; fair value of divi...
1 answers
We have explored the use of logistic regression for when the dependent variable has two classes,...
We have explored the use of logistic regression for when the dependent variable has two classes, Yes or No, Admit or Not, etc. Suppose that there are m (>2) classes. For example, Buy, Sell, or Hold. How will you model this using logistic regression? You don't have to solve it, but provide a s...
1 answers
The destination socket is 60.171.18.22:161. The destination host is a(n) well-known server client ephemeral server server
The destination socket is 60.171.18.22:161. The destination host is a(n) well-known server client ephemeral server server...
1 answers
Which of the following solutions contains the highest [H3O+] ? A) A concentrated solution of a...
Which of the following solutions contains the highest [H3O+] ? A) A concentrated solution of a weak acid B) a dilute solution of strong acid C) a dilute solution of a weak acid D) we cannot tell from the information given...
1 answers
29) The peptidoglycan chain is made up of polymers of a) alanine and glycine b) cytosine...
29) The peptidoglycan chain is made up of polymers of a) alanine and glycine b) cytosine and guanine e) glucose and ribose d) ATP and protein N-acetylmuramic acid and N-acetylglocosamine 30) Safranin is a counterstained used in the gram stain procedure because a) cells will not stain gram positive w...
1 answers
The Production Department of Hruska Corporation has submitted the following forecast of units to be produced by quarter...
The Production Department of Hruska Corporation has submitted the following forecast of units to be produced by quarter for the upcoming fiscal year: 2nd 3rd 4th 1st Quarter Quarter Quarter Quarter Units to be 12,000 10,000 13,000 14,000 produced Each unit requires 0.2 direct labor-hours and direct ...
1 answers
Currently, Forever Flowers Inc. has a capital structure consisting of 25% debt and 75% equity. Forever's debt currently...
Currently, Forever Flowers Inc. has a capital structure consisting of 25% debt and 75% equity. Forever's debt currently has an 8% yield to maturity. The risk-free rate (rRF) is 6%, and the market risk premium (rM - rRF) is 7%. Using the CAPM, Forever estimates that its cost of equity is currentl...

-- 0.011546--