This question is based mainly on material in Unit 8. A skeleton NetBeans project TMA03Q1 is provided.

In this part of the question you are asked to program two concurrent threads and to observe their interaction.

  • Open the project TMA03Q1 and add two new classes according to the following specification:
    • Salt implements Runnable and has a run() method that prints "Salt * " five times successively, without a newline, sleeping for 10 milliseconds before executing each print statement
    • Pepper extends Thread and has a run() method that prints "Pepper * " four times successively, without a newline, sleeping for 10 milliseconds before executing each print statement.
  • Add a constructor to Pepper that takes a string as a parameter and sets the name of the thread to the received string, using the setName method inherited from the Thread class.
  • Add statements where indicated to the main() method in class Main that will create an instance of Pepper whose name is set to "Grinder" and an instance of Salt, and start two concurrently executing threads, one based on each class.
  • Run the project. Copy an example of the output from a program run into your TMA 03 Solution Document. Explain what you saw when you ran the program several times.
  • Copy your Salt and Pepper classes, and your main() method, into your TMA 03 Solution Document.

Class Pepper extended Thread whereas Salt implemented Runnable. Explain why a programmer who needs to use concurrent threads in Java cannot always do so simply by extending the class Thread.

Now add the following lines to the main() method where indicated by the comment, after the part (a) code.

System.out.println("Omelette eaten");

Run the program again. What happens? Briefly explain this result.

How can you make main wait for the Salt and Pepper threads to finish before the omelette is eaten? Show the changes you would make to the project in order to achieve this. Hint: Check the Thread API for a suitable method.

Academic Honesty!
It is not our intention to break the school's academic policy. Projects posted are only used as a reference and should not be submitted as is. We are not held liable for any misuse of the solutions. Please see the frequently asked questions page for further questions and inquiries.
Kindly fill out the form. Please provide a valid email address and we'll get back to you in less than 24 hours. We will be sending an invoice through PayPal upon confirmation. We are a non profit organization however we need an amount to keep this organization running, and to be able to complete our research and development.