You are on page 1of 10

Lab Manual for Advance Computer Programming

Lab-11
Thread Synchronization
Lab 11: Thread Synchronization

Table of Contents
1. Introduction 116

2. Activity Time boxing 116

3. Objective of the experiment 117

4. Concept Map 117


4.1 Example 117

5. Homework before Lab 118


5.1 Problem Solution Modeling 118
5.1.1 Problem 1: 118
5.1.2 Problem 2: 119
5.2 Practices from home 119
5.2.1 Task-1 119
5.2.2 Task-2 119

6. Procedure& Tools 119


6.1 Tools 119
6.2 Setting-up JDK 1.7 [Expected time = 5mins] 119
6.2.1 Compile a Program 119
6.2.2 Run a Program 119
6.3 Walkthrough Task [Expected time = 30mins] 119
6.3.1 Using synchronized keyword. 120

7. Practice Tasks 120


7.1 Practice Task 1 [Expected time = 20mins] 120
7.2 Practice Task 2 [Expected time = 20mins] 120
7.3 Practice Task 3 [Expected time = 20mins] 121
7.4 Practice Task 4 [Expected time = 20mins] 121
7.5 Out comes 121
7.6 Testing 121

8. Evaluation criteria 122

9. Further Reading 123


9.1 Books 123
9.2 Slides 123

Department of Computer Science, Page 115


C.U.S.T.
Lab 11: Thread Synchronization

Lab8: Thread Synchronization


1. Introduction

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.

Relevant Lecture Material

a) Revise Lecture No. 15 and 16


b) Text Book: Java: How to Program by Paul J. Deitel, Harvey M. Deitel
1. Read pages: 837-848
2. Revise the threads implemented in the last lab.

2. Activity Time boxing

Table 1: Activity Time Boxing


Task No. Activity Name Activity time Total Time
5.1 Evaluation of Design 20mins 20mins
6.2 Setting-upPath for JDK 5mins 5mins
6.3 Walkthrough Tasks 30mins 30mins
7 Practice tasks 10mins for each task 30mins
8 Midterm Exam 90min 90mins

Department of Computer Science, Page 116


C.U.S.T.
Lab 11: Thread Synchronization

3. Objective of the experiment

 To learn to save time of performing operations in an application task by task controlling


creation and management of threads
 To learn concurrent programming skills using threads.
 To understand Life and working cycle of a thread.
 To be able to initiate and manage multiple threads.
 To be able to share a single resource between multiple threads using the “synchronized”
construct.

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.");
}
}
}

class ThreadDemo extends Thread {


private Thread t;
private String threadName;
PrintDemo PD;

ThreadDemo( String name, PrintDemo pd) {


threadName = name;
PD = pd;
}

public void run() {


synchronized(PD) {
PD.printCount();
}
System.out.println("Thread " + threadName + " exiting.");
}

public void start () {


System.out.println("Starting " + threadName );
if (t == null) {
t = new Thread (this, threadName);
t.start ();

Department of Computer Science, Page 117


C.U.S.T.
Lab 11: Thread Synchronization

}
}
}

public class TestThread {

public static void main(String args[]) {


PrintDemo PD = new PrintDemo();

ThreadDemo T1 = new ThreadDemo( "Thread - 1 ", PD );


ThreadDemo T2 = new ThreadDemo( "Thread - 2 ", PD );

T1.start();
T2.start();

// wait for threads to end


try {
T1.join();
T2.join();
} catch ( Exception e) {
System.out.println("Interrupted");
}
}
}
Output
Starting Thread - 1
Starting Thread - 2
Counter --- 5
Counter --- 4
Counter --- 3
Counter --- 2
Counter --- 1
Thread Thread - 1 exiting.
Counter --- 5
Counter --- 4
Counter --- 3
Counter --- 2
Counter --- 1
Thread Thread - 2 exiting.

5. Homework before Lab


You must solve the following problems at home before the lab.

5.1 Problem Solution Modeling

After reading the reference material mentioned in the introduction, now you are ready to perform
homework assigned to you.

5.1.1 Problem 1:

Write down the benefits of thread synchronization, with example.

Department of Computer Science, Page 118


C.U.S.T.
Lab 11: Thread Synchronization

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 Practices from home

Solve the following subtasks.

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

In this section you will study create a synchronized thread.

6.1 Tools

Java Development Kit (JDK) 1.7

6.2 Setting-up JDK 1.7 [Expected time = 5mins]

Refer to Lab 1 sec 6.2.

6.2.1 Compile a Program

Refer to Lab 1 sec 6.2 for details.

6.2.2 Run a Program

Refer to Lab 1 sec 6.2 for details.

6.3 Walkthrough Task [Expected time = 30mins]

This task is designed to guide you towards discovering the ways to manage the synchronized
threads and how the threads interact with each other.

Department of Computer Science, Page 119


C.U.S.T.
Lab 11: Thread Synchronization

6.3.1 Using synchronized keyword.

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.

Following process will guide you how to use synchronized keyword.

1. Create a normal thread and add the synchronized keyword like following.

public class ThreadDemo {

public synchronized void saveMessage(String msg){


log.writeln(msg);
}
public void saveMessage2(String msg){
synchronized(this){
log.writeln(msg);
}
}
}

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

7.1 Practice Task 1 [Expected time = 20mins]

7.2 Practice Task 2 [Expected time = 20mins]

Department of Computer Science, Page 120


C.U.S.T.
Lab 11: Thread Synchronization

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.

7.3 Practice Task 3 [Expected time = 20mins]

7.4 Practice Task 4 [Expected time = 20mins]

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.

7.5 Out comes

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.

Test Cases for Practice Task-1


Sample Output
Thread1,5,main
Thread2,5,main
1
10
2
9
3
8
4
7
5
6
6
5
7
4
8
3
9
2
10

Department of Computer Science, Page 121


C.U.S.T.
Lab 11: Thread Synchronization

Test Cases for Practice Task-2

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

Test Cases for Practice Task-3& Task-4

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).

Table 3: Evaluation of the Lab


Sr. No. Task No Description Marks

Department of Computer Science, Page 122


C.U.S.T.
Lab 11: Thread Synchronization

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

This section provides the references to further polish your skills.

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$\

Department of Computer Science, Page 123


C.U.S.T.

You might also like