0% found this document useful (0 votes)
14 views85 pages

Ch6 Thread

Uploaded by

turegn
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views85 pages

Ch6 Thread

Uploaded by

turegn
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 85

Multitasking and Multithreading

0 Multitasking:
0 refers to a computer's ability to perform multiple jobs concurrently
0 more than one program are running concurrently, e.g., UNIX, Windows
0 Multithreading:
0 A thread is a single sequence of execution within a program
0 refers to multiple threads of control within a single program
0 each program can run multiple threads of control within it.
0 Ex: in a Web browser we may do the following tasks at the same time:
1. scroll a page,
2. download an applet or image,
3. play sound,
4 print a page.
0 A thread is a single sequential flow of control within a program.

Chapter 6 (Thread) 2
Concurrency vs. Parallelism
CPU CPU1 CPU2

Chapter 6(Thread) 3
Threads and Processes
CPU

main

run

Process 1 Process 2 Process 3 Process 4

GC

Chapter 4 (Thread) 4
What Are Processes and Threads?
0 There are 3 levels of executions of computer instructions on a computer
system:
 CPU Level: There is only one flow of execution on the central processing
unit (CPU), that is the operating system (OS).
 OS Level: For a multi-tasking OS, multiple application programs can be
managed to be executed simultaneously. Here, a flow of execution is
called a process.
 Application Level: For a well written application program, multiple
sections of codes can be managed to be executed simultaneously. Here, a
flow of execution is called a thread. A program that can manage
multiple threads is called a multi-threading program.
0 A good example of multi-threading programs are computer games that
simulate real time activities of multiple human characters and/or moving
objects.
0 Under the Java architecture, the Java virtual machine (JVM) will provide all
the help you need to create and manage multiple threads in your Java
applications.
5
Chapter 4 (Thread)
What are Threads Good For?
0 To maintain responsiveness of an application during a long running
task
0 To enable cancellation of separable tasks
0 Some problems are naturally parallel
0 To monitor status of some resource (e.g., DB)
0 Some APIs and systems demand it (e.g., Swing)
0 Single-user programs/clients
0 continuously responsive user interfaces
0 e.g., make help menu accessible during time-consuming
database operation, etc.
0 Speed up tasks when multiple processors available
0 Servers
0 Allows multiple client connections simultaneously
Chapter 4 (Thread) 6
Introduction to thread
0 A thread is a single flow of control like simple program.
0 A unique property of java is multithreading only because java
supports multithreading.
0 More than one thread (program) run simultaneously is known as
multithreading (multiprogramming).
0 In multithreading java interpreter handles the switching of control
between the threads in such a way that it looks like they are running
concurrently.
0 Multithreading is useful in a number of ways. We can divide a long
program into number of threads and executes them in parallel.
0 We are going to learn so many useful things in thread lets start with
single main thread.

Chapter 4 (Thread) 7
Application Thread
0 When we execute an application:
1. The JVM creates a Thread object whose task is
defined by the main() method
2. The JVM starts the thread
3. The thread executes the statements of the program
one by one
4. After executing all the statements, the method
returns and the thread dies

Chapter 6 (Thread) 8
Multiple Threads in an Application
0 Each thread has its private run-time stack
0 If two threads execute the same method, each will have its own copy
of the local variables and the methods
0 However, all threads see the same dynamic memory, i.e., heap
0 Two different threads can act on the same object and same static
fields concurrently

Chapter 4 (Thread) 9
The Main Thread
0 When our simple program starts, one single thread begins running
immediately. This is called our single main thread.
0 The main thread is created automatically when program is started.
0 It is very important thread because of two reason.
1. From the main thread other child thread will be created.
2. Main thread is all most every time stop running lastly because it
has to remove or shutdown few resources as well as few action.
0 Now the question is how can we control our main thread?
0 Actually by calling the method currentThread() of Thread class we
can control our main thread.

Chapter 4 (Thread) 10
The Main Thread(cont)
//A program to find out the thread used by JVM to execute the
statements.
class FirstDemo {
public static void main(String[] args) {
System.out.println("Let's find current thread.. ");
Thread th=Thread.currentThread();
System.out.println("Current thread is: "+th);
System.out.println("Thread name is: "+th.getName());
System.out.println("Thread priority is: "+th.getPriority());
System.out.println("Thread is alive: "+th.isAlive());
} Output
} Let's find current thread..
Current thread is: Thread[main,5,main]
Thread name is: main
Chapter 4 Thread
(Thread) priority is: 5 11
Thread is alive: true
The Main Thread(cont)
EX:
public class SecondDemo {
public static void main(String args[]) {
Thread t = Thread.currentThread();
System.out.println("Current thread: " + t);

// change the name of the thread


t.setName("My Thread");
System.out.println("After name change: " + t);
try {
for(int n = 5; n > 0; n--) {
System.out.println(n); //print number with interval of 1 sec.
Thread.sleep(1000); //Thread is going to sleep for 1 sec.
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted");
}
}
}
Chapter 4 (Thread) 12
The Main Thread(cont)
Output:
Current thread: Thread[main,5,main]
After name change: Thread[My Thread,5,main]
5
4
3
2
1

0 Here first of all we give reference of our current main single thread to
t by thread object and currentThread() method.
0 The number 5 to 1 will be print at interval of 1 second due to sleep
method.
0 Thread will go to sleep for 1000 milliseconds due to sleep method

Chapter 4 (Thread) 13
Thread Life Cycle
0 Thread has many different state through out its life.
1. Newborn State
2. Runnable State
3. Running State
4. Blocked State
5. Dead State
0 Thread should be in any one state of the above and it can be move
from one state to another by different methods and ways.

Chapter 4 (Thread) 14
Thread Life Cycle(cont)

Chapter 4 (Thread) 15
Thread Life Cycle(cont)
1) Newborn State
0 When we create a thread it will be in Newborn State.
0 The thread is just created still its not running.
0 We can move it to running mode by invoking the start() method and
it can be killed by using stop() method.

Chapter 4 (Thread) 16
Thread Life Cycle(cont)
2) Runnable State
0 It means that thread is now ready for running and its waiting to give
control.
0 We can move control to another thread by yield() method.

Chapter 4 (Thread) 17
Thread Life Cycle(cont)
3) Running State
0 It means thread is in its execution mode because the control of CPU
is given to that particular thread.
0 It can move in three different situation from running mode.

Chapter 4 (Thread) 18
Thread Life Cycle(cont)
These all are different
methods which can be apply
on running thread and how
the state is changing and
how we can come in our
original previous state using
different methods.

19
Chapter 4 (Thread)
Thread Life Cycle(cont)
4) Blocked State
0 A thread is called in Blocked State when it is not allowed to entering
in Runnable State or Running State.
0 It happens when thread is in waiting, suspended or in sleeping
mode.

5) Dead State
0 When a thread is completed executing its run() method the life cycle
of that particular thread is end.
0 We can kill thread by invoking stop() method for that particular
thread and send it to be in Dead State.

Chapter 4 (Thread) 20
Thread Methods
void start()
0 Creates a new thread and makes it runnable
0 This method can be called only once
void run()
0 The new thread begins its life inside this method
void stop() (deprecated)
0 The thread is being terminated
void yield()
0 Causes the currently executing thread object to temporarily pause
and allow other threads to execute
0 Allow only threads of the same priority to run
void sleep(int m) or sleep(int m, int n)
0 The thread sleeps for m milliseconds, plus n nanoseconds

Chapter 4 (Thread) 21
Creating Thread
0 We can create thread in java with two different ways.
1. Extending the Thread Class.
2. Implements runnable interface.
0 Let’s try to understand step by step both of this.

Chapter 4 (Thread) 22
Creating Thread(cont)
1. Extending the Thread class:
0 In this method one normal class extends the inbuilt class thread and
override its run() method with the code required by that particular
thread.
0 Here we are going to extend class java.lang.Thread. so we can access
all the methods of thread class.
0 Create one class which extends the thread class.
0 Override the run method and put lines of code inside thread method
that will be perform by thread.
0 Create an object of class which we created with extending the thread
class and call the start() method to execute the thread.

Chapter 4 (Thread) 23
Creating Thread(cont)
0 Let’s have a thread named MyThread.
Class MyThread extends Thread {
………………..
………………..
}
0 Implementing the run() method
Public void run() {
………
// Thread code here
}
0 Starting new Thread
MyThread aTh = new MyThread(); // instantiates a new object aTh
aTh.start(); // invokes run() method

Chapter 4 (Thread) 24
Creating Thread(cont)
public class ThirdDemo extends Thread{
public static void main(String[] a) {
ThirdDemo t = new ThirdDemo ();
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 program.
Hello world! - From a thread.
Chapter 4 (Thread) 25
Creating Thread(cont)
0 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. The sub-
thread executes all the statements in the run() method.
 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 all its threads has reached
the end of their execution. In our example, the main thread will end after
printing its message. But the sub-thread will need about one hour to execute
the sleep() call statement. So the entire program will not terminate until the
sub-thread ends.
 The run() method in the Thread is empty, so if you want a thread to do some
work, you need to override the run() method.
Chapter 4 (Thread) 26
Creating Thread(cont)
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++){
System.out.println("From thread B i = " + i);
}
System.out.println("Exit from B");
}
}
Chapter 4 (Thread) 27
public class FourthDemo {
Creating Thread(cont)
public static void main(String[] args) {
//A a = new A().start();
//or
//A a = new A();
//a.start();
//or
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 A i = 1
} From thread A i = 2
} From thread A i = 3
From thread A i = 4
From thread A i = 5
Exit from A
End of main thread
Thread B
From thread B i = 1
From thread B i = 2
From thread B i = 3
From thread B i = 4
Chapter 4 (Thread) From thread B28i = 5
Exit from B
Creating Thread(cont)
Output 2 0 Here you can see that both outputs are different
Thread A
From thread A i = 1 though our program code is same.
From thread A i = 2 0 It happens in thread program because they are
End of main thread
From thread A i = 3 running concurrently on their own.
From thread A i = 4 0 Threads are running independently of one another
Thread B
From thread A i = 5 and each executes whenever it has a chance.
From thread B i = 1
Exit from A
From thread B i = 2
From thread B i = 3
From thread B i = 4
From thread B i = 5
Exit from B

Chapter 4 (Thread) 29
Creating Thread(cont)
2) Implementing the Runnable interface:
0 In this method we have one interface named runnable and we
implements this interface for implementing a thread.
0 Create one class which implements runnable interface.
0 Override the run() method and put some line of code for that
particular thread.
0 Now create an object of inbuilt thread class and create an object of
class that implements runnable interface.
0 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.
0 Call the start() method to run the thread.

Chapter 4 (Thread) 30
Creating Thread(cont)
class FifthDemo implements Runnable {
public static void main(String[] a) {
FifthDemo r = new FifthDemo();
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);
} catch (InterruptedException e) {
System.out.println("Interrupted.");
}
}
}
Output:
Hello world! - From the main program.
Hello world! - From a thread.
Chapter 4 (Thread) 31
Creating Thread(cont)
0 Note that:
 The program behaves the same way as the previous program ThirdDemo
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. If you start a Thread object created in
this way, the run() method of the Runnable object will be executed as a
new thread.
 Since our class is not extending the Thread class any more, we need to call
the sleep() explicitly by prefixing the class name: Thread.
0 May be you are wondering why we need the second way of creating a new
thread, which seems to be less straight forward than the first way? The
answer is that Java classes can not be extended from two different base
classes. So if you are in a situation where you want to create a new class by
extending an existing class to inherit some nice features of that class, and you
also want to make the new class executable as a thread, you have to use the
second way to implement the "Runnable" interface in your new class.
Chapter 4 (Thread) 32
Creating Thread(cont)
Output
class X implements Runnable { End of main Thread
public void run() { Inside X thread
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 = " +i); From xthread i = 4
} From xthread i = 5
System.out.println("Exit from X"); From xthread i = 6
} From xthread i = 7
} From xthread i = 8
public class SixthDemo{ From xthread i = 9
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");
}
}
Chapter 4 (Thread) 33
Extending Thread vs. Implementing
Runnable Interface
0C
•hoosing between these two is a matter of taste
0•
Implementing the Runnable interface
0 May take more work since we still
•
Declare a Thread object
•
Call the Thread methods on this object
0 Your class can still extend other class
0•
Extending the Thread class
0 Easier to implement
0 Your class can no longer extend any other class

Chapter 4 (Thread) 34
The Thread Class: Constructor

Chapter 4 (Thread) 35
The Thread Class: Constants
0 Contains fields for priority values

Chapter 4 (Thread) 36
The Thread Class: Methods
0 Some Thread methods

Chapter 4 (Thread) 37
Thread Priority
0 Each java thread has its own priority which decides the order of
thread to be schedule.
0 The threads of equal priority will be given same treatment by java
scheduler. And they will follow the FCFS (First Come First Serve)
algorithm.
0 User can also set the priority of thread by using the setPriority()
method as follow:
ThreadName.setPriority(int Number);
0 Here the number is integer value between 1 to 10, Here 1 is
minimum priority 10 is maximum priority.
0 The Thread class defines few priority constants:
0 MIN_PRIORITY = 1
0 NORM_PRIORITY = 5
0 MAX_PRIORITY = 10
0 In any Thread the default priority is NORM_PRIORITY
Chapter 4 (Thread) 38
Thread Priority(cont)
0 In multithreading by assigning priority we can answer an
input as quickly as we want.
0 Whenever more than one threads are ready to run java
system select the highest priority thread and execute it
0 If another thread of higher priority comes ,the running
thread will be preempted(blocked) by the incoming thread
and current thread will move to runnable state.

Chapter 4 (Thread) 39
Thread Priority(cont)
class TA extends Thread {
public void run() {
System.out.println("ThreadTA strated");
for(int i = 1; i<=5; i++) {
System.out.println("\t From ThreadTA i = " +i);
}
System.out.println("Exit from TA");
}
}
class TB extends Thread {
public void run() {
System.out.println("ThreadTB strated");
for(int j = 1; j<=5; j++) {
System.out.println("\t From ThreadTB j = " +j);
}
System.out.println("Exit from TB");
}
} Chapter 4 (Thread) 40
Thread Priority(cont)
public class SeventhDemo {
public static void main(String[] args) {
TA threadTA = new TA();
TB threadTB = new TB();
Output
Start Thread TA
threadTA.setPriority(Thread.MIN_PRIORITY); Start Thread TB
threadTB.setPriority(threadTA.getPriority()+3); ThreadTA strated
End of main Thread
From ThreadTA i = 1
System.out.println("Start Thread TA"); From ThreadTA i = 2
threadTA.start(); From ThreadTA i = 3
From ThreadTA i = 4
From ThreadTA i = 5
System.out.println("Start Thread TB"); Exit from TA
threadTB.start(); ThreadTB strated
From ThreadTB j = 1
From ThreadTB j = 2
System.out.println("End of main Thread"); From ThreadTB j = 3
} From ThreadTB j = 4
} From ThreadTB j = 5
Exit from TB
Chapter 4 (Thread) 41
Thread Priority(cont)
0 In the previous example you can see that we start
ThreadTA first but ThreadTB completed its task first
because of higher priority.
0 But again it is multithreading so we all know that output
may be vary each time you run the program.

Chapter 4 (Thread) 42
Race condition & How to Solve it
0•
Race conditions occur when multiple, asynchronously
executing threads access the same object (called a shared
resource) returning unexpected (wrong) results
0•
Example: Threads often need to share a common resource i.e.
a file, with one thread reading from the file while another
thread writes to the file. They can be avoided by
synchronizing the threads which access the shared resource

Chapter 4 (Thread) 44
Method one An Unsynchronized Example
class PrintStringsThread implements Runnable {
Thread thread;
String str1, str2;
PrintStringsThread(String str1, String str2) {
this.str1 = str1;
this.str2 = str2;
thread = new java.lang.Thread(this);
thread.start();
}
public void run() {
System.out.print(this.str1);
try {
java.lang.Thread.sleep(2000);
}catch (InterruptedException ie) { }
System.out.println(this.str2);
}
}
Chapter 4 (Thread) 45
Method one An Unsynchronized Example
public class RaceConditionDemo{
public static void main(String[] args) {
new PrintStringsThread("Hello ", “comps.");
new PrintStringsThread("How are ", "you?");
new PrintStringsThread("Thank you ", "very much!");
}
}
Sample outputs:
Hello How are Thank you comps. Hello How are Thank you you?
you? very much!
very much! comps.

Hello How are Thank you comps. Hello Thank you How are comps.
very much! very much!
you? you?
Chapter 4 (Thread) 46
Method two An Unsynchronized Example
public class RaceConditionDemoTwo {
public static void main(String[] args) {
new PrintStringsThread2("Hello ", "comps.").start();
new PrintStringsThread2("How are ", "you?").start();
new PrintStringsThread2("Thank you ", "very much!").start();
}
}
class PrintStringsThread2 extends Thread {
String str1, str2;
PrintStringsThread2(String str1, String str2) {
this.str1 = str1;
this.str2 = str2;
}
public void run() {
System.out.print(this.str1);
try {
java.lang.Thread.sleep(2000);
}catch (InterruptedException ie) { }
System.out.println(this.str2);
} Chapter 4 (Thread) 47
}
Unsynchronized Example
0 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.
0 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?
0 If the threads are running independently, the following could
happen:

Chapter 4 (Thread) 48
Unsynchronized Example

0 Both you and your friend will receive $50.00 each, and your
account will still have $50.00. The bank could lose $50.00.
0 The solution to this problem Chapter
is synchronization.
4 (Thread) 49
Synchronization: Locking an Object
0•
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.
0 Synchronization uses a lock to represent the shared data to allow
each thread to use the lock status to Synchronize with each other.
0 Synchronization code block is a unit of code in a thread that
requires synchronization on a particular lock.
0 More synchronization locks or longer synchronization code blocks
slow down application performance.
0 A thread is synchronized by becoming an owner of the object's
monitor
0 Consider it as locking an object
0 •A thread becomes the owner of the object's monitor in one of these
ways
0 Option 1: Use synchronized method
0 Option 2: Use synchronized statement on a common object
Chapter 4 (Thread) 50
Synchronization: Locking an Object
0 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
locked, the execution will be stopped until the lock is unlocked. If the
lock is unlocked, the lock will be locked, and 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.
0 Now let's see if we can use the synchronization technique in the bank
application program to help the bank. Let's define a synchronization
block starting from the "Get Account Balance" action to the "Set Account
Balance" action in each thread, and associate the block with a lock. With
this change, both you and yourChapter
friend can still withdraw $50.00, but 51your
4 (Thread)
account will have nothing left:
Synchronization: Locking an Object

0 The synchronization technique did help the bank from losing money. But
it also increased the total transaction time.
Chapter 4 (Thread) 52
How Java Supports Synchronization?
0 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.
0 Java also offers three ways to define synchronized blocks.

Chapter 4 (Thread) 53
How Java Supports Synchronization?
Way 1) Synchronized Class Method:
class class_name {
static synchronized return_type method_name() {
//statement block
}
}
0 All the statements in the method become the synchronized block, and
the class object is the lock.

Chapter 4 (Thread) 54
How Java Supports Synchronization?
Way 2) Synchronized Instance Method:
class class_name {
synchronized return_type method_name() {
//statement block
}
}
0 All the statements in the method become the synchronized block, and
the instance object is the lock.

Chapter 4 (Thread) 55
How Java Supports Synchronization?
Way 3) Synchronized Statement:
class class_name {
return_type method_name() {
synchronized (object) {
statement block
}
}
}
0 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.

Chapter 4 (Thread) 56
How Java Supports Synchronization?
0 Java applies the synchronization rule by assigning the ownership of
the lock's monitor to the threads that are running the synchronized
blocks. Here is how it works:
When a synchronized clock is reached in an execution thread, it will
try to gain the ownership of the monitor of the lock object. If
another thread owns the lock's monitor, it will wait.
Once the lock's monitor is free, the waiting thread will become the
owner of the lock's monitor, and start to execute the synchronized
block.
Once the synchronized block is executed to the end, the lock's
monitor will be freed again.
0 Note that one program can have many locks and each lock can be
associated with many different synchronized blocks. But the
synchronization rule only applies between the synchronized block and
its associated lock.
Chapter 4 (Thread) 57
How Java Supports Synchronization?
0 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
}
}
0 Block 1 will never be executed at the same time as block 2.

Chapter 4 (Thread) 58
How Java Supports Synchronization?
0 The following code defines two synchronized blocks. But they are
associated with two different locks, one is the class object, and the
other is the instance object.

class class_name {
type method_name() {
synchronized (this) {
statement block 1
}
}
static synchronized type method_name() {
statement block 2
}
}
0 The two synchronized blocks will never wait for each other.
Chapter 4 (Thread) 59
How Java Supports Synchronization?
0 Exercise: Assuming the following class is used in a multiple-threaded
program:
 Is it possible that block_1 in one thread
could be on hold because of block_1 is
public class C {
running another thread?
public static synchronized void m1() {
 Is it possible that block_1 in one thread
statement block_1
could be on hold because of block_2 is
}
running another thread?
public synchronized void m2() {
 Is it possible that block_2 in one thread
statement block_2
could be on hold because of block_1 is
}
running another thread?
public synchronized void m3() {
 Is it possible that block_2 in one thread
statement block_3
could be on hold because of block_2 is
}
running another thread?
public void m4() {
 Is it possible that block_2 in one thread
synchronized (this) {
could be on hold because of block_3 is
statement block_4
running another thread?
}
 Is it possible that block_2 in one thread
}
could be on hold because of block_4 is
} Chapter 4 (Thread) 60
running another thread?
Deposit as a Synchronized method
0 Assume we have a method called deposit in Account class. So here is how
to make it synchronized.

class Account {
int balance=0;

public synchronized void deposit(int amount) {

int tmp = balance;


Thread.sleep(200);
balance = tmp + amount;

System.out.println("Current balance is "+balance);


}
}//Account

Chapter 4 (Thread) 61
Option 1: Use synchronized method
class TwoStrings {
synchronized static void print(String str1, String str2) {
System.out.print(str1);
try {
Thread.sleep(500);
} catch (InterruptedException ie) { }
System.out.println(str2);
}
}
class PrintStringsThread implements Runnable {
Thread thread;
String str1, str2;
PrintStringsThread(String str1, String str2) {
this.str1 = str1;
this.str2 = str2;
thread = new Thread(this);
thread.start();
}
public void run() {
TwoStrings.print(str1, str2);
} Chapter 4 (Thread) 62
}
Option 1: Use synchronized method
public class SynchDemoOne {
public static void main(String[] args) {
new PrintStringsThread("Hello ", "comps.");
new PrintStringsThread("How are ", "you?");
new PrintStringsThread("Thank you ", "very much!");
}
}

Output
Hello comps.
How are you?
Thank you very much!

Chapter 4 (Thread) 63
Option 2: Use synchronized statement on a common object
class TwoStrings {
static void print(String str1, String str2) {
System.out.print(str1);
try {
Thread.sleep(500);
} catch (InterruptedException ie) { }
System.out.println(str2);
}
}
class PrintStringsThread implements Runnable {
Thread thread;
String str1, str2;
TwoStrings ts;
PrintStringsThread(String str1, String str2, TwoStrings ts) {
this.str1 = str1;
this.str2 = str2;
this.ts = ts;
thread = new Thread(this);
thread.start();
}
public void run() {
synchronized (ts) {
ts.print(str1, str2);
}
Chapter 4 (Thread) 64
}
}
Option 2: Use synchronized statement on a common object
public class SynchDemoTwo {
public static void main(String[] args) {
TwoStrings ts = new TwoStrings();
new PrintStringsThread("Hello ", "comps.", ts);
new PrintStringsThread("How are ", "you?", ts);
new PrintStringsThread("Thank you ", "very much!", ts);
}
}

Output
Hello comps.
How are you?
Thank you very much!

Chapter 4 (Thread) 65
Synchronizing threads
0 Java use the monitor concept to achieve mutual exclusion and
synchronization between threads.
0 Synchronized methods /statements guarantee mutual exclusion.
0 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.
0 wait(), notify() and notifyAll() control the synchronization of
threads.
0 Allow one thread to wait for a condition (logical state) and
another to set it and then notify waiting threads.
0 condition variables => instance boolean variables
0 wait => wait();
0 notifying => notify(); notifyAll();
Chapter 4 (Thread) 66
Difference between Wait and Sleep
0 Main difference between wait and sleep is that wait() method release the
acquired monitor when thread is waiting while Thread.sleep() method
keeps the lock or monitor even if thread is waiting. Also wait method in
java should be called from synchronized method or block while there is no
such requirement for sleep() method.
0 Another difference is Thread.sleep() method is a static method and
applies on current thread, while wait() is an instance specific method
and only got wake up if some other thread calls notify method on same
object. also in case of sleep, sleeping thread immediately goes to Runnable
state after waking up while in case of wait, waiting thread first acquires
the lock and then goes into Runnable state. So based upon your need if you
require a specified second of pause use sleep() method or if you want to
implement inter-thread communication use wait method.

Chapter 4 (Thread) 67
Difference between Wait and Sleep
0 here is list of difference between wait and sleep in Java :
1) wait is called from synchronized context only while sleep can be
called without synchronized block
2) wait is called on Object while sleep is called on Thread.
3) waiting thread can be awake by calling notify and notifyAll while
sleeping thread can not be awaken by calling notify method.
4) wait is normally done on condition, Thread wait until a condition
is true while sleep is just to put your thread on sleep.
5) wait release lock on object while waiting while sleep doesn’t
release lock while waiting.

Chapter 4 (Thread) 68
Difference between yield and sleep
0 Major difference between yield and sleep in Java is that yield() method
pauses the currently executing thread temporarily for giving a chance to
the remaining waiting threads of the same priority to execute. If there is
no waiting thread or all the waiting threads have a lower priority then the
same thread will continue its execution. The yielded thread when it will
get the chance for execution is decided by the thread scheduler whose
behavior is vendor dependent. Yield method doesn’t guarantee that
current thread will pause or stop but it guarantee that CPU will be
relinquish by current Thread as a result of call to Thread.yield() method in
java.
0 Sleep method in Java has two variants one which takes millisecond as
sleeping time while other which takes both mill and nano second for
sleeping duration.
0 sleep(long millis) or sleep(long millis,int nanos)
0 Cause the currently executing thread to sleep for the specified number
of milliseconds plus the specified number of nanoseconds.
Chapter 4 (Thread) 69
Points about Thread sleep() method
1) Thread.sleep() method is used to pause the execution, relinquish the CPU
and return it to thread scheduler.
2) Thread.sleep() method is a static method and always puts current thread on
sleep.
3) Java has two variants of sleep method in Thread class one with one argument
which takes milliseconds as duration for sleep and other method with two
arguments one is millisecond and other is nanosecond.
4) Unlike wait() method in Java, sleep() method of Thread class doesn't
relinquish the lock it has acquired.
5) sleep() method throws Interrupted Exception if another thread interrupt a
sleeping thread in java.
6) With sleep() in Java its not guaranteed that when sleeping thread woke up it
will definitely get CPU, instead it will go to Runnable state and fight for CPU with
other thread.
7) There is a misconception about sleep method in Java that calling t.sleep() will
put Thread "t" into sleeping state, that's not true because Thread.sleep method is
a static method it always put current thread into Sleeping state and not thread "t".
Chapter 4 (Thread) 70
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. Synchronization in java guarantees
that no two threads can execute a synchronized method which requires same lock
simultaneously or concurrently.
2. You can use java synchronized keyword only on synchronized method or
synchronized block.
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.
Lock is released even if thread leaves synchronized method after completion or due
to any Error or Exception.
4. Java Thread acquires an object level lock when it enters into an instance
synchronized java method and acquires a class level lock when it enters into static
synchronized java method.
5.java synchronized keyword is re-entrant in nature it means if a java
synchronized method calls another synchronized method which requires same lock
then current thread which is holding lock can enter into that method without
acquiring lock.
6. Java Synchronization will throw NullPointerException if object used in java
synchronized block is null e.g. synchronized (myInstance) will throws
NullPointerException if myInstance isChapter
null. 4 (Thread) 71
Important points of synchronized keyword in Java
7. 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.
8. One limitation of java synchronized keyword is that it can only be used to
control access of shared object within the same JVM. If you have more than one JVM
and need to synchronized access to a shared file system or database, the java
synchronized keyword is not at all sufficient. You need to implement a kind of global
lock for that.
9. Java synchronized keyword incurs performance cost. Synchronized method in
Java is very slow and can degrade performance. So use synchronization in java when
it absolutely requires and consider using java synchronized block for synchronizing
critical section only.
10. Java synchronized block is better than java synchronized method in java
because by using synchronized block you can only lock critical section of code and
avoid locking whole method which can possibly degrade performance. A good
example of java synchronization around this concept is getInstance() method
Singleton class. See here.
11. Its possible that both static synchronized and non static synchronized
method can run simultaneously or concurrently because they lock on different
object.
Chapter 4 (Thread) 72
Important points of synchronized keyword in Java
12. From java 5 after change in Java memory model reads and writes are atomic
for all variables declared using volatile keyword (including long and double
variables) and simple atomic variable access is more efficient instead of accessing
these variables via synchronized java code. But it requires more care and attention
from the programmer to avoid memory consistency errors.
13. Java synchronized code could result in deadlock or starvation while
accessing by multiple thread if synchronization is not implemented correctly.
14. According to the Java language specification you can not use java synchronized
keyword with constructor it’s illegal and result in compilation error. So you can not
synchronized constructor in Java which seems logical because other threads cannot
see the object being created until the thread creating it has finished it.
15. You cannot apply java synchronized keyword with variables and can not use
java volatile keyword with method.
16. Java.util.concurrent.locks extends capability provided by java synchronized
keyword for writing more sophisticated programs since they offer more capabilities
e.g. Reentrancy and interruptible locks.
17. java synchronized keyword also synchronizes memory. In fact java
synchronized synchronizes the whole of thread memory with main memory.

Chapter 4 (Thread) 73
Important points of synchronized keyword in Java
18. Important method related to synchronization in Java are wait(), notify() and
notifyAll() which is defined in Object class.
19. Do not synchronize on non final field on synchronized block in Java. because
reference of non final field may change any time and then different thread might
synchronizing on different objects i.e. no synchronization at all. example of
synchronizing on non final field :

private String lock = new String("lock");


synchronized(lock){
System.out.println("locking on :" + lock);
}
any if you write synchronized code like above in java you may get warning
"Synchronization on non-final field" in IDE like Netbeans and InteliJ

Chapter 4 (Thread) 74
Important points of synchronized keyword in Java
20. Its not recommended to use String object as lock in java synchronized block
because string is immutable object and literal string and interned string gets stored
in String pool. so by any chance if any other part of code or any third party library
used same String as there lock then they both will be locked on same object despite
being completely unrelated which could result in unexpected behavior and bad
performance. instead of String object its advised to use new Object() for
Synchronization in Java on synchronized block.

private static final String LOCK = "lock"; //not recommended


private static final Object OBJ_LOCK = new Object(); //better

public void process() {


synchronized(LOCK) {
........
}
}

21. From Java library Calendar and SimpleDateFormat classes are not thread-safe
and requires external synchronization in Java to be used in multi-threaded
environment.
Chapter 4 (Thread) 75
What Is Deadlock?
0 Deadlock: A state of execution when 2 or more threads are all put on
hold, because each of them is holding a synchronization lock while
waiting for another lock. The lock each thread is waiting for is held by
one of the other threads. So none of threads can move forward.
0 By definition, deadlock can only happen when the program is
running multiple threads, and multiple locks are being used by
multiple threads. Therefore:
A single-threaded program will never have deadlocks.
A program with one lock will never have deadlocks.
0 Deadlock is a state of execution when 2 or more threads are all put on
hold waiting for others to release locks.
0 Deadlock is demonstrated with the 5 dining philosophers simulation
program.
0 Here is a simple program to demonstrate a deadlock with two
threads and two locks:
Chapter 4 (Thread) 76
What Is Deadlock?
import java.util.*;
public class DeadLockDemo extends Thread {
public static Object l1 = new Object();
public static Object l2 = new Object();
private int index;
public static void main(String[] a) {
Thread t1 = new Thread1();
Thread t2 = new Thread2();
t1.start();
t2.start();
}
private static class Thread1 extends Thread {
public void run() {
synchronized (l1) {
System.out.println("Thread 1: Holding lock 1...");
try { Thread.sleep(10); }
catch (InterruptedException e) {}
System.out.println("Thread 1: Waiting for lock 2...");
synchronized (l2) {
System.out.println("Thread 2: Holding lock 1 & 2...");
}
}
} Chapter 4 (Thread) 77
}
What Is Deadlock?
private static class Thread2 extends Thread {
public void run() { Output:
synchronized (l2) { Thread 1: Holding lock 1...
System.out.println("Thread 2: Holding lock 2..."); Thread 2: Holding lock 2...
try { Thread.sleep(10); } Thread 1: Waiting for lock 2...
catch (InterruptedException e) {} Thread 2: Waiting for lock 1...
System.out.println("Thread 2: Waiting for lock 1...");
synchronized (l1) {
System.out.println("Thread 2: Holding lock 2 & 1...");
}
}
}
}
}

0 As the output shows, after gaining lock 1, thread 1 was put on hold to
wait for lock 2, which was held by thread 2 and it will never be
release, because thread 2 was also put on hold to wait lock 1, which
was held by thread1. So none of them could move forward. You have
to press Ctrl-C to stop program.
Chapter 4 (Thread) 78
What Is Deadlock?
Deadlock Example - 5 Dining Philosophers
0 The story of 5 dining philosophers is the most interesting illustration of the
deadlock problem.
0 "Five philosophers are sitting at a round table. In front of each
philosopher is a bowl of rice. Between each pair of philosophers is
one chopstick. Before an individual philosopher can take a bite of
rice, he must have two chopsticks, one taken from the left, and
one taken from the right. The philosophers must find some way
to share chopsticks such that they all get to eat. "
0 Deadlock will occur in this story, if all philosophers are taking the
chopstick from the left side at the same time, and no one is
willing to put down the chopstick until he gets the chopstick on
the right side.

Chapter 4 (Thread) 79
Daemon threads
 We 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.
 You can indicate a thread is a daemon thread by calling the
Thread.setDaemon() method. You might want to use daemon
threads for background threads that you create in your programs,
such as timer threads or other deferred event threads, which are
only useful while there are other non-daemon threads running.
Chapter 4 (Thread) 80
Garbage Collection
0 Garbage Collector: is an execution thread that automatically frees
up the memory occupied by unused objects. The garbage collector is
managed by the JVM and executed separately from the application
program main thread.
0 Garbage Collection: is the process during which the garbage
collector actively identifying unused objects, and remove them to
frees up the memory.
0 There are two key questions involved in the garbage collection:
How garbage collector identifies objects as unused objects?
When garbage collector performs the collection process?
0 Unused Object: is an object that has zero live reference pointing to it.
Java does not provide us any facilities to check how many references
are there for a given object. But we can read the program source code
to figure this out.
0 Garbage collector is an independent thread always running in the
Java Virtual Machine (JVM).
Chapter 4 (Thread) 81
Garbage Collection
0 Garbage collector automatically removes unused objects when the free
space of the allocated memory is low.
0 gc() method can be called to perform garbage collection explicitly.
0 If you do not like the way JVM automatically performing the garbage
collection process. you can use the gc() method of the default Runtime
object to control the garbage collection process by yourself.

Chapter 4 (Thread) 82
Garbage Collection
0 For example, after executing the following section of code:
String a = new String("Apple");
a = new String("Banana);
new String("Orange");
String g = sub("Grape");
String x = "Kiwi";
String y = x;
x = null;
...
static String sub(String b) {
String l = new String{"Peach");
return new String("Pear");
}
0 objects created by the code will have the following status:

Chapter 4 (Thread) 83
Garbage Collection
0 String object of "Apple": Unused, because the only reference from "a" is gone
now. "a" is pointing to another object now.
0 String object of "Banana": Used, because it is still referred by "a".
0 String object of "Orange": Unused, because it was created, but never
referenced by any variables.
0 String object of "Grape": Unused, because the reference from "b" is gone
now. "a" is out of scope now after the execution of the method sub().
0 String object of "Peach": Unused, because the reference from "l" is gone now.
"l" is out of scope now after the execution of the method sub().
0 String object of "Pear": Used, because the reference returned from the
method sub() is in "g" now.
0 String object of "Kiwi": Used, because it is still referred by "y", even the
reference from "x" is gone now.

Chapter 4 (Thread) 84

You might also like