Chapter 3
Chapter 3
2
The human body performs a great variety of operations in
parallel or concurrently. For example: Respiration, blood
circulation, digestion, thinking and walking, can occur
concurrently.
By using multithreading technique programs can perform different activities at the same time.
3
What are Threads?
Processes – are independently running programs that are isolated
from each other.
Threading - is a facility to allow multiple activities to coexist
within a single process.
Java is the first programming language to explicitly include
threading within the language itself.
Threads are sometimes referred to as lightweight processes.
Like processes, threads can be independent, concurrent paths of
execution through a program, and each thread has its own stack,
its own program counter, and its own local variables.
However, threads within a process are less insulated from each
other than separate processes are.
4 They share memory, file handles, and other per-process state.
What are Threads? (contd)
A process can support multiple threads, which appear to execute
simultaneously and asynchronously to each other.
More than one thread (program) run simultaneously is known as
multithreading (multiprogramming).
Multiple threads within a process share the same memory address,
which means they have access to the same variables and objects,
and they allocate objects from the same heap.
Every Java program has at least one thread -- the main thread.
The JVM also creates other threads that are mostly invisible to you
– for example: threads associated with garbage collection and
other JVM housekeeping tasks.
Other facilities create threads too, such as the AWT (Abstract
Windowing Toolkit) or Swing UI toolkits, servlet containers,
5
application servers, and RMI (Remote Method Invocation).
Why Use Threads?
Some of the reasons for using threads
are:
7
Thread Risks
While the Java thread facility is very easy to use, there are
several risks you should try to avoid when you create
multithreaded programs.
When multiple threads access the same data item, make
sure that they coordinate their access to a shared data so
that both see a consistent.
The Java language provides two keywords for this
purpose: synchronized and volatile.
If you are going to use synchronization to protect access
to shared variables, you must make sure to use it
everywhere in your program where the variable is
accessed.
8
Thread Life Cycle
A thread can be in one of several possible states through out its life.
1. Newborn State
When we create a thread it will be in Newborn State.
9
Thread Life Cycle (contd)
3. Running State
It means thread is in its execution mode because the control of
CPU is given to that particular thread.
It can move in three different situation from running mode.
4. Blocked State
A thread is called in Blocked State when it is not allowed to
entering in Runnable State or Running State.
It happens when thread is in waiting, suspended or in sleeping
mode.
5. Dead State
When a thread is completed executing its run() method the life
cycle of that particular thread is end.
We can kill thread by invoking stop() method for that particular
10
thread and send it to be in Dead State.
Thread Life Cycle(contd)
11
Thread
void start()
Methods
Makes created threads runnable
This method can be called only once
void run()
The new thread begins its life inside this method
void stop()
The thread is being terminated
void yield()
Causes the currently executing thread object to temporarily pause
and allow other threads to execute
Allow only threads of the same priority to run
14
Creating Thread(contd)
Example: MyThread.
Class MyThread extends Thread
{
………………..
………………..
}
Implementing the run() method
public void run()
{
……… // Thread code here
}
Starting new Thread
MyThread aTh = new MyThread(); // instantiates a new
aTh.start(); // invokes run() method
15
Creating Thread(contd)
Example One:
public class ThreadDemo extends Thread{
public static void main(String[] a) {
ThreadDemo t = new ThreadDemo ();
t.start();
System.out.println("Hello world! - From the main
program.");
}
public void run() {
System.out.println("Hello world! - From a
thread.");
try {
sleep(1000*60*60);
} catch (InterruptedException e) {
System.out.println("Interrupted.");
Output:
} Hello world! - From the main
16
} program.
Creating Thread(contd)
A couple of things you should know about this
program:
This program will run (actually sleep) for about one
hour, after printing those messages. So you may
need to press Ctrl-C to terminate the program.
There will be actually two threads running in this
program. The first one is the main thread executing
all the statement in the main() method. The second
one is a sub-thread launched by the t.start()
statement.
Notice the order of the messages printed out on the
console. It tells us that the sub-thread took a little
bit longer to run its first statement, after it has
been launched by the main thread.
A multi-threading program will not terminate until
17
all its threads has reached the end of their
Creating Thread(contd)
import java.lang.Thread;
class A extends Thread{
public void run(){
System.out.println("Thread A");
for(int i=1;i<=5;i++){
System.out.println("From thread
A i = " + i);
}
System.out.println("Exit from A");
}}
class B extends Thread {
public void run(){
System.out.println("Thread B");
for(int i=1;i<=5;i++){
18 System.out.println("From thread
B i = " + i);
Creating Thread(contd)
public class Demo {
public static void main(String[] args) {
new A().start();//creating A class thread object and
calling run method
new B().start();//creating B class thread object and
calling run method
System.out.println("End of main thread");
Thread A
} From thread Ai
=1
}
From thread Ai
• Running the same program will yield =2
different output though our program From thread Ai
=3
code is same. From thread Ai
=4
• It happens in thread program because From thread Ai
they are running concurrently on their =5
Exit from A
own. End of main
•19 Threads are running independently of thread
Thread B
one another and each executes
Creating Thread(contd)
2) Implementing the Runnable interface:
In this method we have one interface named runnable and we
implements this interface for implementing a thread.
Create one class which implements runnable interface.
Override the run() method and put some line of code for that particular
thread.
Create an object of class that implements runnable interface and create an
object of inbuilt Thread class.
Give the reference of object to thread object by passing an argument
(argument must be the object of class which implements the
runnable interface) while creating a thread object.
Call the start() method to run the thread.
20
Creating Thread(contd)
Example One:
class ThreadRun implements Runnable {
public static void main(String[] a) {
ThreadRun r = new ThreadRun();
Thread t = new Thread(r);
t.start();
System.out.println("Hello world! - From the
main program.");
}
public void run() {
System.out.println("Hello world! - From a
thread.");
try {
Thread.sleep(1000*60*60);
Output:
} catch (InterruptedException e) {the main
Hello world! - From
21
System.out.println("Interrupted.");
program.
} Hello world! - From a thread.
Note that:
The program behaves the same way as the previous program
ThreadDemo which is created using thread objects with thread sub
classes
The Thread object t is created with the special Thread constructor,
which takes a Runnable object as input..
Since our class is not extending the Thread class any more, we need to
call the sleep() explicitly by prefixing the class name: Thread.
Compare the first and second techniques:
Implementing Runnable Interface takes further steps, creating object
of the class which will be the argument of the Thread constructor
and we need to use Thread to access sleep method Explicitly .
(Extending Thread is simpler than implementing Runnable)
In java multiple inheritance is not allowed. Hence, if there is a class
that we need to inherit we have to not inherit Thread class rather
implement Runnable interface so that we can have chance of
22 inheriting other class that we need to inherit.
Creating Thread(contd)
Example Two: Output
End of main Thread
class X implements Runnable {
Inside X thread
public void run() { From xthread i = 1
System.out.println("Inside X thread"); From xthread i = 2
for(int i=1;i<=10;i++) { From xthread i = 3
System.out.println("From xthread i = "From
+i); xthread i = 4
From xthread i = 5
} From xthread i = 6
System.out.println("Exit from X"); From xthread i = 7
}} From xthread i = 8
From xthread i = 9
public class Demo{ From xthread i = 10
public static void main(String[] args) { Exit from X
X x1 = new X(); //class object
//creating thread object and giving reference of class
object to thread object
Thread xthread = new Thread(x1);
xthread.start();
System.out.println("End of main Thread");
23
}}
What You Should Know
A thread doesn't actually begin to execute until another thread calls
the start() method on the Thread object for the new thread.
A thread will end in one of three ways:
24
to complete: the join() method.
Thread Priority
Each java thread has its own priority which decides the order of
thread to be schedule.
The threads of equal priority will be given same treatment by java
scheduler. And they will follow the FCFS (First Come First Serve)
algorithm.
User can also set the priority of thread by using the setPriority()
method as follow:
ThreadName.setPriority(int Number);
Here the number is integer value between 1 to 10, Here 1 is
minimum priority 10 is maximum priority.
The Thread class defines few priority constants:
MIN_PRIORITY = 1
NORM_PRIORITY = 5
MAX_PRIORITY = 10
In any Thread the default priority is NORM_PRIORITY
25
Thread Scheduling
Scheduling
Except when using Thread.join() and Object.wait(), the
timing of thread scheduling and execution is nondeterministic
or round-robin scheduling.
26
Sleeping
The Thread API includes a sleep() method, which will cause the
current thread to go into a wait state until the specified amount of
time has elapsed or until the thread is interrupted by another
thread calling Thread.interrupt() on the current thread's Thread
object.
When the specified time elapses, the thread again becomes runnable
and goes back onto the scheduler's queue of runnable threads.
If a thread is interrupted by a call to Thread.interrupt(), the sleeping
thread will throw an InterruptedException so that the thread will
know that it was awakened by an interrupt and won't have to check to
see if the timer expired.
The Thread.yield() method is like Thread.sleep(), but instead of
sleeping, it simply pauses the current thread momentarily so that
other threads can run.
27 In most implementations, threads with lower priority will not run
Daemon Threads
It’s mentioned that a Java program exits when all of its threads have
completed, but this is not exactly correct.
What about the hidden system threads, such as the garbage collection
thread and others created by the JVM? We have no way of stopping
these. If those threads are running, how does any Java program ever
exit?
These system threads are called daemon threads. A Java program
actually exits when all its non-daemon threads have completed.
Any thread can become a daemon thread.
29
Thread Synchronization
Unsynchronized Example
The biggest problem of allowing multiple threads sharing the same
data set is that one operation in one thread could collide with
another operation in another threads on the same data. When this
happens, the result is un-desirable.
Let's use a bank application program as an example. Assuming that
the program has multiple threads running, with each thread
connecting one ATM system, and you have a saving account in the
bank with $100.00, now you and your friend are going to two
different ATMs at about the same time, and trying to withdraw
$50.00 from your account, what do you think it will happen?
If the threads are running independently, the following could
happen:
Both you and your friend will receive $50.00 each, and your account
will still have $50.00. The bank could lose $50.00.
The solution to this problem is synchronization.
30
Synchronization: Locking an Object
Synchronization is needed in a multi-threading application to
ensure that one thread is updating a shared data other threads wait
and get the updated value.
Synchronization uses a lock to represent the shared data to allow
each thread to use the lock status to Synchronize with each other.
Synchronization code block is a unit of code in a thread that
requires synchronization on a particular lock.
More synchronization locks or longer synchronization code
blocks slow down application performance.
31
Synchronization: Locking an Object
Synchronization is a programming technique that involves
3 elements:
Lock: An object with two states: locked and unlocked.
Synchronized Block: A block of statements that is
associated with a lock.
Synchronization Rule: When a synchronized block
is encountered in a thread of execution, the
associated lock will be checked.
If the lock is locked, the execution will be stopped until the lock is
unlocked. If the lock is unlocked, the synchronized block of statements
will be executed. When the execution reaches the end of the
synchronized block, the lock will be unlocked. With this rule, two
synchronized blocks associated with same lock will never be executed
at the same time.
32
How
Java Supports Synchronization?
Instead of let the programmers to design their own locks,
manage the synchronization blocks, and apply the synchronization
rules, Java offers a synchronization monitor on each instance of
the Object class, so it can be used as a synchronization lock. Since
all classes are sub classes of Object, all objects in Java can be used
as synchronization locks.
Java also offers three ways to define synchronized blocks.
33
How Java Supports Synchronization?
Way 1) Synchronized Class Method:
class class_name {
static synchronized return_type
method_name() {
//statement block
}
}
All the statements in the method become the
synchronized block, and the class object is
the lock.
34
How Java Supports Synchronization?
Way 2) Synchronized Instance Method:
class class_name {
synchronized return_type method_name() {
//statement block
}
}
All the statements in the method become the
synchronized block, and the instance object is
the lock.
35
How Java Supports Synchronization?
Way 3) Synchronized Statement:
class class_name {
return_type method_name() {
synchronized (object) {
statement block
}
}
}
All the statements specified in the parentheses of the
synchronized statement become the synchronized
block, and the object specified in the statement is the
lock.
36
How Java Supports Synchronization?
For example, the following code defines two synchronized
blocks. Both are associated with the same lock, the instance
object.
class class_name {
type method_name() {
synchronized (this) {
statement block 1
}
}
synchronized type method_name() {
statement block 2
}
}
37Block 1 will never be executed at the same time as block 2.
Synchronizing Threads
Java use the monitor concept to achieve mutual exclusion
and synchronization between threads.
Synchronized methods /statements guarantee mutual
exclusion.
Mutual exclusion may cause a thread to be unable to complete its
task. So monitor allow a thread to wait until state change and then
continue its work.
wait(), notify() and notifyAll() control the synchronization
of threads.
Allow one thread to wait for a condition (logical state) and another
to set it and then notify waiting threads.
38
Important points of synchronized keyword
in Java
1. Synchronized keyword in Java is used to provide mutual exclusive
access of a shared resource with multiple threads in Java.
2. Synchronization in java guarantees that no two threads can execute a
synchronized method which requires same lock simultaneously or
concurrently.
3. When ever a thread enters into java synchronized method or block it
acquires a lock and whenever it leaves java synchronized method or
block it releases the lock.
4. One Major disadvantage of java synchronized keyword is that it
doesn't allow concurrent read which you can implement using
java.util.concurrent.locks.ReentrantLock.
5. Java synchronized keyword incurs performance cost.
6. You cannot apply java synchronized keyword with variables and can
not use java volatile keyword with method.
7.39Important method related to synchronization in Java are wait(),
notify() and notifyAll() which is defined in Object class.