Lab10: Threads
This is a simple lab to demonstrate the most basic threading implementation. You can easily write this lab in 30 lines or less.
We will write a method that counts from 0-4, then we will run several threads of that method simultaneously.
This lab will not deal with any of the potential problems caused by concurrency. We can revisit those problems once we have first implemented the basics.
The Assignment
You are going to create a Lab10 class with the following requirements:
- All of the code that you generate for this lab must be in a file named Lab10.java
- Your program must include a private method named print() that includes the
following code at a minimum:
private void print() { for (int i=0; i<5; i++) { System.out.println(i); Thread.sleep(400); } } - You must use threads to run the print() method multiple times in parallel
- The user must be able to specify the number of threads to run as a command-line argument. e.g. "java Lab10 3" must run the above print statement simultaneously in three separate threads.
- Your program must recognize if the user does not supply any command-line arguments, and print a helpful message
- Your program must recognize if the user supplies an argument that is not an integer, and print a helpful message
- You are not required to use javadoc for this lab
- Any implementation that prints the correct output without using threads will receive a grade of 0
Sample output
$ java Lab10 3 0 0 0 1 1 1 2 2 2 3 3 3 4 4 4 $ java Lab10 99 0 0 0 0 0 0 0 0 ... $ java Lab10 Usage: java Lab10 <number of threads> $ java Lab10 asdf Usage: java Lab10 <number of threads> Could not parse: 'asdf'
Example of incorrect output
If you see this, you did something wrong...
$ java Lab10 3 0 1 2 3 4 0 1 2 3 4 0 1 2 3 4
What to hand in
Lab10.java
Your file must be in a directory named 'Lab10'
Delete any *.class or other unneeded files prior to submitting
When you run the submit script, the directory and its contents get zipped and sent to your instructor. Ask for help early if you are having problems running the submit script.
Make sure that you run the correct submit script for your instructor:
- CDR Blenkhorn: /courses/blenk/submit Lab10
- Dr. Taylor: /courses/taylor/submit Lab10