Distributed Systems Lab: Java Threads
In this lab, we will work with two toy programs to experiment with several
features of Java threads.
1. Concurreny
Have a look at the
Zipper
class and explain what it does.
Compile and run the code. Does the result meet your expectation?
2. Creating Threads from Runnable Objects
Modify the code of Zipper so that you create threads from Runnable objects.
Here, you can find a
sample solution.
3. Threads Falling Asleep
Modify the new code of Zipper so that
your threads fall asleep for a nanosecond after having printed their teeth.
How does the behaviour of the zipper change?
Here, you can find a
sample solution.
4. Thread Priorities
Modify the code of Zipper (i.e., the version without sleeping threads)
so that one thread has minimal priority and the other one has
has maximal priority.
What happens?
Here, you can find a
sample solution.
5. Thread Interference
The class Banking models a scenario where
two bank clerks, John and Jim, are accessing a bank account to add a
certain amount of money to that account.
John wants to add 50 Quid while Jim wants to add 100 Quid.
Each clerk is modeled by a thread.
Bank accounts can be accessed by a get and a set method. The access
methods print to standard output what they are currently doing.
Explain what goes wrong in this scenario and why this is case.
6. Thread Synchronization
Use method synchronization to avoid interference in the example above.
Here, you can find a
sample solution.
7. Deadlocks
Extend the banking scenario to show how synchronization can lead to deadlocks.
Here, you can find a
sample solution.
8. Avoiding Deadlocks
Improve your code from the previous exercise so that it can run without thread
interference and without creating deadlocks.
Here, you can find a
sample solution.
Back to the labs page