Lab 10 Simple Thresds

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 11

Lab Manual for Advance Computer Programming

Lab-10
Simple Threads
Lab 10: Simple Thread

Table of Contents
1. Introduction 107

2. Activity Time boxing 108

3. Objective of the experiment 108

4. Concept Map 108


4.1 Threads 108
4.2 Thread Class Steps 108
4.3 Working Cycle of a thread 109
4.4 Runnable Interface 109

5. Homework before Lab 110


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

6. Procedure& Tools 110


6.1 Tools 110
6.2 Setting-up JDK 1.7 [Expected time = 5mins] 111
6.2.1 Compile a Program 111
6.2.2 Run a Program 111
6.3 Walkthrough Task [Expected time = 30mins] 111
6.3.1 Basic Thread Creation using Thread class: 111
6.3.2 Using the Runnable interface 112

7. Practice Tasks 112


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

8. Evaluation criteria 115

9. Further Reading 115


9.1 Books 115
9.2 Slides 115

Department of Computer Science, Page 106


C.U.S.T.
Lab 10: Simple Thread

Lab 10: Simple Threads


1. Introduction

One other strong feature provided by Java is the support for multi-threaded applications.
Threaded applications are made such that multiple tasks can be performed concurrently. For
example, Microsoft Word, it responds to the keys on keyboard and mouse events, no matter how
extensive reformatting text or updating the display is carried on. Another example could be like
when you play a game on computer. You will notice that all aspects of game are executing
simultaneously. This concurrency is achieved using the concept of threads. Individual tasks are
performed in individual threads at the same time so the application may run in an uninterrupted
way without breaks.

Assuming that you have developed the basic understanding of threads. It is very important that
you understand the life cycle of a thread. Figure 1 shows the life cycle of a thread. Basically a
thread is born when you instantiate an object of your thread class. Thread starts when you call a
start() method on the thread object. After starting the thread goes in a ready to be scheduled state
where it waits for its turn or wait for resources from processor. As soon as it gets the resources
then it is said to be in running state. When it finishes its running then it goes to the dead state.
After the running and before the dead state the thread can go to the blocked state. This is the state
which is normally caused by the synchronized methods when one thread is executing the
synchronized method then the other thread who wants the same resources has to wait for its turn.
This waiting time can be simple referred to as a thread’s blocked state.

Figure 1: Life Cycle of a thread

This blocked state has basically three different further states which are known as the working
cycle of the thread. The working cycle is discussed later in the concept map section. Readings
relevant to this introduction are mentioned in the “Relevant Lecture Material”. You must consult
this before lab.

Department of Computer Science, Page 107


C.U.S.T.
Lab 10: Simple Thread

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

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

4.1 Threads

Threads provide the ability to do multiple things at one time within the same application.
Threads are lightweight and easy to create and destroy. There are two methods of creating
threads:
1. Through Runnable Interface
2. Through Thread class
The Runnable interface will be implemented in the next lab. In this lab you will only use the
following method.

4.2 Thread Class Steps

1. Extend the Thread Interface

classThreadExample extends Thread

Department of Computer Science, Page 108


C.U.S.T.
Lab 10: Simple Thread

2. Override run method

public void run ( ){


// write what you want the thread to do
}

3. Instantiate Thread object by passing thread name in constructor

ThreadExample w = new ThreadExample (“first thread”);

4. Start thread

w.start();

4.3 Working Cycle of a thread

There are three different states in the working cycle of the thread.

3. Sleep state
4. Wait state
5. Blocked state

The sleep state is initiated by the thread itself. The thread calls the sleep() method by passing the
time in millisecondto the sleep() function. Sleep() is a static method therefore it always executes
on the current thread. Following code shows how sleep method is called.

java.lang.Thread.sleep(1000);

The time given in arguments is in milliseconds that means when you pass 1000 your current
thread will go to sleep for one second.

The wait state is another state in which the thread is not in running state. A thread always calls
the wait() method on itself but unlike sleep it does not come out of wait state after some time.
The thread in wait state only comes out of wait state when any other thread notifies the thread in
wait state using the notify() method.

The Blocked state is also a state where processor is ready to allocate resources to the thread but,
it does not acquire resource as it is waits for some external input or some event to occur.

4.4 Runnable Interface

Since Java doesn’t support multiple inheritance therefore there are times when we need to create
a thread in an existing system. So far we have studied that the way to create a thread is by
extending the current class with the “Thread” class. If we are introducing a thread in existing
implemented system then there is a chance that the class in which we want to extend Thread

Department of Computer Science, Page 109


C.U.S.T.
Lab 10: Simple Thread

class is already inheriting some other class. For such scenario Java has provided the alternate to
implement a runnable interface. The runnable interface provides the same features as the thread
class thereby providing the alternate to inheriting the thread class.

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:

Make a list of static methods in java.lang.Thread class and identify the scenarios in which we use
the yield() method.

5.1.2 Problem 2:

Write the pseudo to write a data in the same file with multiple threads.

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

Department of Computer Science, Page 110


C.U.S.T.
Lab 10: Simple Thread

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.

6.3.1 Basic Thread Creation using Thread class:


Following code shows how to write a WorkerThread class which will execute independently.

public class WorkerThread extends Thread {


private String job ;
public WorkerThread (String j ){
job = j;
}
public void run ( ) {
for(inti=1; i<= 5; i++)
System.out.println(job number + " = " + i);
}
}

//****Driver class
public class TestThread{
public static void main (String args[ ]){
WorkerThread first = new WorkerThread (“first thread”);
WorkerThread second = new WorkerThread (“second thread”);
WorkerThread third = new WorkerThread (“third thread”)
Thread t1 = new Thread (first );
Thread t2 = new Thread (second);
Thread t3 = new Thread (third);
t1.start();
t2.start();
t3.start();
}

Department of Computer Science, Page 111


C.U.S.T.
Lab 10: Simple Thread

Now t1, t2 and t3 will run concurrently and will show mixed output as run method is called.
At the end main thread also terminates.

6.3.2 Using the Runnable interface

The following steps will show you how to use the Runnable interface to implement the threads.

1. Create a simple thread as was done in the previous lab.


2. Instead of the statement “extends Thread” use “implements Runnable”. Following
example will show you how it is done.

publicclassThreadDemoimplementsRunnable{

publicvoid run(){
for(inti=1;i<10;i++){
System.out.println(Thread.currentThread().getName()+" "+i);
try{
Thread.sleep(1000);
}catch(Exception e){
System.out.println(e.toString());
}
}
}

publicstaticvoid main(String[]args)throwsException{
ThreadDemo t =newThreadDemo();
t.start();

ThreadDemo t2 =newThreadDemo();
t2.start();
}
}

You will notice that the only difference between the above code and the code from the previous
lab is “implements runnable”. In this way we can implement threads without the consequences of
multiple inheritance.

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

Department of Computer Science, Page 112


C.U.S.T.
Lab 10: Simple Thread

7.1 Practice Task 1 [Expected time = 20mins]


Write a program in which you have to create two threads. Thread one will display its information
and displays counting from 1 to 10. 2 nd thread also displays its information and displays the
counting from 10 to 1. Remember you cannot call the run method yourself, it must be called
using JVM. Give your threads some name as well.

7.2 Practice Task 2 [Expected time = 20mins]

7.3 Practice Task 3 [Expected time = 20mins]

Write a program that creates array of 10 different threads, each thread generates a random
number. The main thread calculates the sum of the numbers generated by the thread and displays
it on screen. Hint: each thread will have to save the generated number somehow.

7.4 Practice Task 4 [Expected time = 20mins]

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

Department of Computer Science, Page 113


C.U.S.T.
Lab 10: Simple Thread

7
4
8
3
9
2
10
1

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.

Department of Computer Science, Page 114


C.U.S.T.
Lab 10: Simple Thread

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
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 115


C.U.S.T.

You might also like