Lab 10 Simple Thresds
Lab 10 Simple Thresds
Lab 10 Simple Thresds
Lab-10
Simple Threads
Lab 10: Simple Thread
Table of Contents
1. Introduction 107
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.
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.
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. Start thread
w.start();
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.
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
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.
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.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.
//****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();
}
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.
The following steps will show you how to use the Runnable interface to implement the threads.
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
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.
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.
7
4
8
3
9
2
10
1
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).
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$\