Distributed Systems Lab: Java Threads



In this lab, we will work with thre 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.

9. Thread Communication

This is an example of two threads that act as producer and consumer. The producer creates data that the consumer needs as input.
Both, the producer and the consumer, operate on a buffer that contains four cells to store characters.
In the example, the producer tries to fill the buffer with new characters while the consumer takes the characters out of the buffer.
We would like that the producer waits when the buffer is filled so that the consumer can continue and likewise that the consumer waits when it has emptied the buffer.
Run the example and find out what is going wrong. What about the usage of resources of the machine?

10. Waiting and Notifying

Threads can temporarily release a monitor on an object if they execute the method wait() on that object.
A thread waiting for an object whose monitor is in the possession of another thread can be woken up if another threat executes the method notify().
Use these two methods in such a way that each thread, instead of running through an empty loop, waits,
and such that each thread, after having completed its work, notifies the other one.


BACK Back to the labs page