Professional Documents
Culture Documents
Lab-11
Thread Synchronization
Lab 11: Thread Synchronization
Table of Contents
1. Introduction 116
In this lab you will learn about the thread synchronization. When we start two or more threads
within a program, there may be a situation when multiple threads try to access the same resource
and finally they can produce unforeseen result due to concurrency issues. For example, if
multiple threads try to write within a same file then they may corrupt the data because one of the
threads can override data or while one thread is opening the same file at the same time another
thread might be closing the same file.
So there is a need to synchronize the action of multiple threads and make sure that only one
thread can access the resource at a given point in time. This is implemented using a concept
called monitors. Each object in Java is associated with a monitor, which a thread can lock or
unlock. Only one thread at a time may hold a lock on a monitor.
Java programming language provides a very handy way of creating threads and synchronizing
their task by using synchronized blocks. You keep shared resources within this block. Following
is the general form of the synchronized statement −
Syntax
synchronized (object identifier) {
// Access shared variables and other shared resources
}
Here, the object identifier is a reference to an object whose lock associates with the monitor that
the synchronized statement represents. Now we are going to see two examples, where we will
print a counter using two different threads. When threads are not synchronized, they print
counter value which is not in sequence, but when we print counter by putting inside
synchronized () block, then it prints counter very much in sequence for both the threads.
4. Concept Map
Here is a simple example which may or may not print counter value in sequence and every time
we run it, it produces a different result based on CPU availability to a thread.
4.1 Example
class PrintDemo {
public void printCount() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("Counter --- " + i );
}
} catch (Exception e) {
System.out.println("Thread interrupted.");
}
}
}
}
}
}
T1.start();
T2.start();
After reading the reference material mentioned in the introduction, now you are ready to perform
homework assigned to you.
5.1.1 Problem 1:
5.1.2 Problem 2:
Write the pseudo to write a data in the same file with multiple threads without using the
synchronized methods.
5.2.1 Task-1
What will happen when a class extends a Thread class and also implements a Runnable interface
at the same time?
5.2.2 Task-2
Explain with a coded example that why is it not recommended to call the run() method in the
main?
6. Procedure& Tools
6.1 Tools
This task is designed to guide you towards discovering the ways to manage the synchronized
threads and how the threads interact with each other.
By the looks the synchronized methods seem to be very difficult but they are pretty simple when
you implement it because all the locking mechanism is maintained by the monitor object
discussed previously. There are two types of utilizations for synchronized keyword. One is
synchronized block and the other is synchronized method. Both of them have almost the same
purpose. The only advantage that a synchronized block has over the other type is that it provides
a kind of flexibility to the programmer by which he gets the ability to synchronize block of
statements or even a single statement.
1. Create a normal thread and add the synchronized keyword like following.
2. First function is a synchronized method and the second contains a synchronized block.
You will notice that there is not much difference and both are doing the same thing. For
both of these methods only a single thread will be able to utilize them. Any other thread
who wants its access will have to wait till the time the lock is released.
7. Practice Tasks
This section will provide more practice exercises which you need to finish during the lab. You
need to finish the tasks in the required time. When you finish them, put these tasks in the
following folder:
\\dataserver\assignments$\Advanced Computer Programming\Lab8
Write a program which has a class having two synchronized methods get() and put(). You have
to create three threads which try to access the synchronized methods simultaneously in a loop of
10. In the get and put method you will display the name of the thread which is accessing the get
method or put method.
Implement a scenario in threads which creates a deadlock between the threads. After that try to
remove that deadlock by introducing a synchronized function.
Note: Dead lock is when two threads attempt to acquire locks on same resource.
After completing this lab, student will be able to understand the usage of Runnable interface and
they will be able to handle and share a resource between multiple threads.
7.6 Testing
This section provides you the test cases to test the working of your program. If you get the
desired mentioned outputs for the given set of inputs then your program is right.
Sample Output
Iteration 1 : Thread1 is accessing the get method
Iteration 1 : Thread1 is accessing the put method
……………
Iteration 10 : Thread1 is accessing the get method
Iteration 10 : Thread1 is accessing the put method
Iteration 1 : Thread2 is accessing the get method
Iteration 1 : Thread2 is accessing the put method
……………
Iteration 10 : Thread2 is accessing the get method
Iteration 10 : Thread2 is accessing the put method
Iteration 1 : Thread3 is accessing the get method
Iteration 1 : Thread3 is accessing the put method
……………
Iteration 10 : Thread3 is accessing the get method
Iteration 10 : Thread3 is accessing the put method
Sample Output
Thread1 generated 10
Thread2generated 5
Thread3generated 3
Thread4 generated 100
Thread5generated 1
Thread6generated 2
Thread7generated 9
Thread8generated 15
Thread9generated 22
Thread10 generated 1
The Sum is: 168
Since the task-2 and task-3 have a randomized behavior there for their test cases will be
explained/provided by the lab instructor at the runtime.
8. Evaluation criteria
The evaluation criteria for this lab will be based on the completion of the following tasks. Each
task is assigned the marks percentage which will be evaluated by the instructor in the lab whether
the student has finished the complete/partial task(s).
1 4 Problem Modeling 20
2 6 Procedures and Tools 10
3 7 Practice tasks and Testing 35
4 8 Midterm Exam 20
5 Comments 5
6 Good Programming Practices 10
9. Further Reading
9.1 Books
Text Book:
Java: How to Program by Paul J. Deitel, Harvey M. Deitel. Eighth Edition
Java Beginners Guide: http://www.oracle.com/events/global/en/java-outreach/resources/java-a-
beginners-guide-1720064.pdf
http://exampledepot.8waytrips.com/ for the package by package examples
9.2 Slides
The slides and reading material can be accessed from the folder of the class instructor available
at \\dataserver\jinnah$\