Java Multithreading Exercises

Table of Contents

This is an individual assignment. You may talk about ideas with others in the class, and you may help each other debug code, but the code that you write should be your own. Any ideas that you get from online should be limited in scope, and you should credit them appropriately via program comments.

Here are a few exercises to give you some practice with Java multithreading. You can use this SumThread example as a starting point, although it might be more useful to start from scratch to make sure you understand all of the steps.

Max value

Write a program called MaxValue.java that finds the maximum value in an array of ints using 4 threads. Your main should be similar as the one in the above-linked SumThread example, though you should construct your array of random numbers instead of increasing numbers. You may assume in your threaded code that the array has at least 4 elements.

Reverse hello

Write a program called ReverseHello.java that creates a thread (let's call it Thread 1). Thread 1 creates another thread (Thread 2); Thread 2 creates Thread 3; and so on, up to Thread 50. Each thread should print "Hello from Thread <num>!", but you should structure your program such that the threads print their greetings in reverse order.

Shared counter

Write a program called SharedCounter.java in which 10 threads each increment a shared int counter 10 times. When all the threads have finished, print the final value of the counter. If the initial value is zero, do you always get 100? Arrange for your code to sometimes print the wrong answer. (Hint: try using some well-placed calls to Thread.yield() or Thread.sleep().)


Submit a zip file to Moodle with your three programs within. Remember that the work will be graded anonymously, so do not include your name anywhere in your code. However, you code should otherwise follow good standards of style, including appropriate comments throughout your program.

Author: Laura Effinger-Dean, with some minor modifications by Dave Musicant

Created: 2015-12-15 Tue 12:01

Emacs 24.3.1 (Org mode 8.2.10)

Validate