Question

In: Computer Science

Using Eclipse to answer this Java question Using the concepts from the Concurrency Basics Tutorial I...

Using Eclipse to answer this Java question

Using the concepts from the Concurrency Basics Tutorial I provided in Modules, write a program that consists of two threads. The first is the main thread that every Java application has. The main thread should create a new thread from the Runnable object, MessageLoop, and wait for it to finish. If the MessageLoop thread takes too long to finish, the main thread should interrupt it. Use a variable named maxWaitTime to store the maximum number of seconds to wait. The main thread should output a message stating that it is still waiting every half second.

The MessageLoop thread should print out a series of 5 messages. It should wait 850 milliseconds between printing messages to create a delay. If it is interrupted before it has printed all its messages, the MessageLoop thread should print "Message loop interrupted" and exit.

Your program must demonstrate that it can both output messages and interrupt the message output. To do this, place your code in main into a for loop using maxWaitTime as the index.

So in main your code will be

for (int maxWaitTime = 1; maxWaitTime <= 5; maxWaitTime++) {

// All of main's processing goes here (All does not mean part of. ALL of main).

}

maxWaitTime means the same as it would in real life. It is how long the main thread waits before interrupting. Think about this. Don't confuse milliseconds and seconds.

Sample output :

maxWaitTime: 1 second(s)
main : Starting MessageLoop thread
main : Waiting for MessageLoop thread to finish
main : Continuing to wait...
main : Continuing to wait...
Thread-0 : 1. All that is gold does not glitter, Not all those who wander are lost
main : MessageLoop interrupted
maxWaitTime: 2 second(s)
main : Starting MessageLoop thread
main : Waiting for MessageLoop thread to finish
main : Continuing to wait...
main : Continuing to wait...
Thread-1 : 1. All that is gold does not glitter, Not all those who wander are lost
main : Continuing to wait...
main : Continuing to wait...
Thread-1 : 2. The old that is strong does not wither, Deep roots are not reached by the frost
main : MessageLoop interrupted
maxWaitTime: 3 second(s)
main : Starting MessageLoop thread
main : Waiting for MessageLoop thread to finish
main : Continuing to wait...
main : Continuing to wait...
Thread-2 : 1. All that is gold does not glitter, Not all those who wander are lost
main : Continuing to wait...
main : Continuing to wait...
Thread-2 : 2. The old that is strong does not wither, Deep roots are not reached by the frost
main : Continuing to wait...
main : Continuing to wait...
Thread-2 : 3. From the ashes a fire shall be woken, A light from the shadows shall spring
main : MessageLoop interrupted
maxWaitTime: 4 second(s)
main : Starting MessageLoop thread
main : Waiting for MessageLoop thread to finish
main : Continuing to wait...
main : Continuing to wait...
Thread-3 : 1. All that is gold does not glitter, Not all those who wander are lost
main : Continuing to wait...
main : Continuing to wait...
Thread-3 : 2. The old that is strong does not wither, Deep roots are not reached by the frost
main : Continuing to wait...
main : Continuing to wait...
Thread-3 : 3. From the ashes a fire shall be woken, A light from the shadows shall spring
main : Continuing to wait...
Thread-3 : 4. Renewed shall be blade that was broken
main : Continuing to wait...
main : MessageLoop interrupted
maxWaitTime: 5 second(s)
main : Starting MessageLoop thread
main : Waiting for MessageLoop thread to finish
main : Continuing to wait...
main : Continuing to wait...
Thread-4 : 1. All that is gold does not glitter, Not all those who wander are lost
main : Continuing to wait...
main : Continuing to wait...
Thread-4 : 2. The old that is strong does not wither, Deep roots are not reached by the frost
main : Continuing to wait...
main : Continuing to wait...
Thread-4 : 3. From the ashes a fire shall be woken, A light from the shadows shall spring
main : Continuing to wait...
Thread-4 : 4. Renewed shall be blade that was broken
main : Continuing to wait...
main : Continuing to wait...
Thread-4 : 5. The crownless again shall be king
main : Done!

Solutions

Expert Solution

Multithreading is a Java feature that allows concurrent execution of two or more parts of a program for maximum utilization of CPU. But it should be noted that at any instance only thread can run.

Threads can be created by using two mechanisms extending the Thread class and Implementing the Runnable Interface.

The program for the above demonstration starts below,

package mythreadpackage;

public class MyThreads {

    // Display a message, the name of the current thread
    static void threadMessage(String message) {
        String threadName =
            Thread.currentThread().getName();
        System.out.format("%s: %s%n",
                          threadName,
                          message);
    }

    private static class MessageLoop
        implements Runnable {
        public void run() {
            String importantInfo[] = {
                "1.All that is gold does not glitter, Not all those who wander are lost",
                "2.The old that is strong does not wither, Deep roots are not reached by the frost",
                "3.From the ashes a fire shall be woken, A light from the shadows shall spring",
                "4.Renewed shall be blade that was broken",
                "5.The crownless again shall be king"
            };
            try {
                for (int i = 0;
                     i < importantInfo.length;
                     i++) {
                       Thread.sleep(850);                 
                    // Print a message
                    threadMessage(importantInfo[i]);
                }
            } catch (InterruptedException e) {
                threadMessage("MessageLoop interrupted");
            }
        }
    }

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

        // To change themaxWaitTime
       for (int maxWaitTime = 1; maxWaitTime <= 5; maxWaitTime++) {
           System.out.println("maxWaitTime: "+maxWaitTime+" seconds");
            threadMessage("Starting MessageLoop thread");
            long startTime = System.currentTimeMillis();
            Thread t = new Thread(new MessageLoop());
            t.start();
  
            threadMessage("Waiting for MessageLoop thread to finish");
            // loop until MessageLoop
            // thread exits
            while (t.isAlive()) {
              
                Thread.sleep(500);
               threadMessage("Continuing to wait...");
                        
                if (((System.currentTimeMillis() - startTime) > maxWaitTime*1000)
                      && t.isAlive()) {
                    threadMessage("MessageLoop interrupted");
                    t.interrupt();
                    // -- wait indefinitely
                    t.join();
                }
            }
            threadMessage("Done!");
        }
    }
}

Please find attached the screenprint of the program and output,


Related Solutions

Using the concepts from the Concurrency Basics Tutorial I provided in Modules, write a program that...
Using the concepts from the Concurrency Basics Tutorial I provided in Modules, write a program that consists of two threads. The first is the main thread that every Java application has. The main thread should create a new thread from the Runnable object, MessageLoop, and wait for it to finish. If the MessageLoop thread takes too long to finish, the main thread should interrupt it. Use a variable named maxWaitTime to store the maximum number of seconds to wait. The...
C++ program using Eclipse IDE The C++ program should have concurrency. The C++ program should create...
C++ program using Eclipse IDE The C++ program should have concurrency. The C++ program should create 2 threads that will act as counters. One thread should count down from 5 to 0. Once that thread reaches 0, then a second thread should be used to count up to 20.
This code has to be in java (I code in eclipse). Also these instructions have to...
This code has to be in java (I code in eclipse). Also these instructions have to be followed exactly because if not my output won't match the expected out ( this will be uploaded on zybooks). Write a program that asks the user for their age in days. The program will compute the person's age in years (you can assume that all years have 365 days) and then prints one of the following messages: If the user is 1 year...
Create a Java application that will exhibit concurrency concepts. Your application should create two threads that will act as counters.
JAVACreate a Java application that will exhibit concurrency concepts. Your application should create two threads that will act as counters. One thread should count up to 20. Once thread one reaches 20, then a second thread should be used to count down to 0.
Using map - java - eclipse Prompt the user for the skillset to add. A skillset...
Using map - java - eclipse Prompt the user for the skillset to add. A skillset can be any String. Examples of skillsets are: “java” “software design”, “databases”, etc. Add the skillset to the logged in user’s skillsets and then provide a response to the logged in user indicating that their skillset has been added (e.g. “Java has been added to your skillsets.”). You don’t have to display any additional messages if the user added a duplicate skillset. In this...
Hello, I need this done with Java and ran in Eclipse if possible. A university wants...
Hello, I need this done with Java and ran in Eclipse if possible. A university wants to demonstrate its political correctness by applying the Supreme Court’s “Separate but equal is inherently unequal” doctrine to gender as well as race. As such, the university has decided that both genders will use the same bathroom facilities. However, in order to preserve some tradition, it decrees that when a woman is in the bathroom, only other women may enter, and when a man...
I need to write a java program (in eclipse) that will read my text file and...
I need to write a java program (in eclipse) that will read my text file and replace specific placeholders with information provided in a second text file. For this assignment I am given a text file and I must replace <N>, <A>, <G>, with the information in the second file. For example the information can be John 22 male, and the template will then be modified and saved into a new file or files (because there will be multiple entries...
This is Java class working on the eclipse. I include some of the codes just so...
This is Java class working on the eclipse. I include some of the codes just so you know what needed. create and work with interfaces you'll create the DepartmentConstants interface presented. In addition, you'll implement an interface named Displayable that's similar to the Printable interface Create the interfaces 1- Import the project named ch12-ex1_DisplayableTest and review the codes package murach.test; public interface Displayable {     String getDisplayText(); } 2 . Note that this code includes an interface named Displayable that...
Explain the difference between concurrency and parallelism. Using these concepts, discuss how a multi-threaded application can...
Explain the difference between concurrency and parallelism. Using these concepts, discuss how a multi-threaded application can run faster than a single-threaded application on a single-processor machine and on a multi-processor machine.
Using Java preferably with Eclipse Task: Write a program that creates a class Apple and a...
Using Java preferably with Eclipse Task: Write a program that creates a class Apple and a tester to make sure the Apple class is crisp and delicious. Instructions: First create a class called Apple The class Apple DOES NOT HAVE a main method Some of the attributes of Apple are Type: A string that describes the apple.  It may only be of the following types:  Red Delicious  Golden Delicious  Gala  Granny Smith Weight: A decimal value representing...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT