Multi Threading

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

TechVeerendra’s

Software Solutions

Multithreading
Multithreading in Java:

Multithreading in java is a process of executing multiple threads


simultaneously.

A thread is a lightweight sub-process, the smallest unit of processing.


Multiprocessing and multithreading, both are used to achieve multitasking.

However, we use multithreading than multiprocessing because threads use a


shared memory area. They don't allocate separate memory area so saves
memory, and context-switching between the threads takes less time than
process.

Java Multithreading is mostly used in games, animation, etc.

Advantages of Java Multithreading:

 It doesn't block the user because threads are independent and you can
perform multiple operations at the same time.
 You can perform many operations together, so it saves time.
 Threads are independent, so it doesn't affect other threads if an
exception occurs in a single thread.
 Multithreading uses very effectively the microprocessor time by reducing
its idle time. When the processor's idle time is reduced, the output of the
programs comes earlier. Multithreading is a concept that should be
supported by the operating system. Now-a-days, all operating systems
support multithreading.

[email protected]
Ph: 9014424466 Page 1
TechVeerendra’s
Software Solutions

Multitasking, Multiprocessing and Multithreading:

Process: A program under execution is called a process.

Multitasking:

Executing several tasks simultaneously is the concept of multitasking. We use


multitasking to utilize the CPU.

There are two types of multitasking's.

o Process-based Multitasking (Multiprocessing)

o Thread-based Multitasking (Multithreading)

Process based multitasking:

Executing several tasks simultaneously where each task is a separate


independent process such type of multitasking is called process based
multitasking.

Example:

 While typing a java program in the editor we can able to listen mp3 audio
songs at the same time we can download a file from the net all these
tasks are independent of each other and executing simultaneously and
hence it is Process based multitasking.
 This type of multitasking is best suitable at "os level".

[email protected]
Ph: 9014424466 Page 2
TechVeerendra’s
Software Solutions

o Each process has an address in memory. In other words, each process


allocates a separate memory area.

o A process is heavyweight.

o Cost of communication between the process is high.

o Switching from one process to another requires some time for saving and
loading registers, memory maps, updating lists, etc.

Note: Shifting between the processes is known as context switching. Do not


shift unnecessarily when the first program is going smooth with its execution
as context switching takes more time and performance looses. Shift only when
a running process is stopped for some reason.

Thread based multitasking:

Executing several tasks simultaneously where each task is a separate


independent part of the same program, is called Thread based multitasking.
And each independent part is called a "Thread".

 This type of multitasking is best suitable for "programatic level".


 When compared with "C++", developing multithreading examples is very
easy in java because java provides in built support for multithreading
through a rich API (Thread, Runnable, ThreadGroup, ThreadLocal...etc).
 In multithreading on 10% of the work the programmer is required to do
and 90% of the work will be down by java API.
 Threads share the same address space.
 A thread is lightweight.
 Cost of communication between the thread is low.

Note: At least one process is required for each thread.

[email protected]
Ph: 9014424466 Page 3
TechVeerendra’s
Software Solutions

The main important application areas of multithreading are:

 To implement multimedia graphics.


 To develop animations.
 To develop video games etc.
 To develop web and application servers

Note:

Whether it is process based or Thread based the main objective of multitasking


is to improve performance of the system by reducing response time.

What is Thread in java?

A thread is a lightweight subprocess, the smallest unit of processing. It is a


separate path of execution.

A Thread represents a separate path of execution of group of statements.

If we write a group of statements then these statements are executed by JVM


one by one this execution called Thread, because JVM uses a thread to execute
these statements .This means in every Java program there is a thread running
internally. This thread is used by JVM to execute the program statements.

Ex:

//To find currently running thread in this program

class Test

{
public static void main(String[] args)

Thread t1=Thread.currentThread();

System.out.println(“Current thread: ”+t1);

[email protected]
Ph: 9014424466 Page 4
TechVeerendra’s
Software Solutions

System.out.println(“its name: ”+t.getName());

Threads are independent. If there occurs exception in one thread, it doesn't


affect other threads. It uses a shared memory area.

As shown in the above figure, a thread is executed inside the process. There is
context-switching between the threads. There can be multiple processes inside
the OS, and one process can have multiple threads.

Note: At a time one thread is executed only.

What is the requirement of the Thread-based multi-tasking?

If only one process exists before the processor and if the process execution is
stopped for some reason, the microprocessor becomes idle without any work.
This type of programming is known as monolithic programming. In
monolithic programming, the whole process constitutes a single module. To get
a better understanding, Lord Buddha statue in Hussain Sagar lake in
Hyderabad, India is a monolithic statue (single stone carvation). The minus

[email protected]
Ph: 9014424466 Page 5
TechVeerendra’s
Software Solutions

point of single stone is if some part is to be replaced in long future, the whole
statue is to be replaced. The same is the problem with monolithic programming
also; if a part of the program is stopped, the whole program comes to standstill.
There comes to the rescue multithreading.

A Java process can be divided into a number of threads (or to say, modules)
and each thread is given the responsibility of executing a block of statements.
That is, a thread is an in charge of a few statements of a program. If one thread
stops its execution, the execution control can be shifted to another thread.
Remember, here all threads belong to the same process. This is the advantage
of threads over monolithic programming. The ultimate result is
microprocessor idle time is reduced. The end result is output of the program
comes earlier.

A thread is a part of a process. A thread lives within a process. No process, no


thread. To understand better, we cannot keep our brain outside for some time
and place it back; it is because brain is a part of human body. Similarly, a

[email protected]
Ph: 9014424466 Page 6
TechVeerendra’s
Software Solutions

thread cannot be there without a process. Infact, a process is divided into a


number of threads.

Definition of thread: a thread is a single sequential flow of control within a


process". It is something confusing. These statements are executed one-by-one
sequentially. Every thread maintains its own execution context within a
process context area. We can say, a thread is a sub process. For execution, one
thread does not depend on other; every thread is independent of other. 

Lightweight Process and Heavyweight Process:

If the execution shifts between the threads of the same process, it is known
as lightweight process. If the execution shifts between the threads of different
processes, it is known as heavyweight process.

If the control shifts between the threads t1 and t2 of the same process p1, it is


known as lightweight process.

If the control shifts between the threads t1 of process p1 and t1 of process p2,


it is known as heavyweight process. Generally, threads are designed to be
lightweight because heavyweight is a big overhead to the OS.

[email protected]
Ph: 9014424466 Page 7
TechVeerendra’s
Software Solutions

Java API support for Threads

Multithreading is one of the built-in and important feature of Java language.


Java's built-in classes, useful to develop a multithreaded program, are here
under and all are from java.lang package.

Java Thread class

Java provides Thread class to achieve thread programming. Thread class


provides constructors and methods to create and perform operations on a
thread. Thread class extends Object class and implements Runnable interface.

CLASS USEFUL METHODS

sleep(), join(), suspend(), resume(), stop()


Thread and run() etc.

Runnable
interface only run() method

Object wait(), notify() and notifyAll()

getName(), getParent() and activeCount()


ThreadGroup etc.

Common Exceptions in Threads:


The following are common exceptions that come in thread programming. All are
from java.lang package.

1. InterruptedException : It is thrown when the waiting or sleeping state is


disrupted by another thread.

[email protected]
Ph: 9014424466 Page 8
TechVeerendra’s
Software Solutions

2. IllegalStateException : It is thrown when a thread is tried to start that is


already started.

Creating Java Thread

We can define a Thread in the following 2 ways.

1. By extending Thread class.

2. By implementing Runnable interface.

Thread class:

Thread class provide constructors and methods to create and perform


operations on a thread. Thread class extends Object class and implements
Runnable interface.

Commonly used Constructors of Thread class:

o Thread()

o Thread(String name)

o Thread(Runnable r)

o Thread(Runnable r,String name)

Commonly used methods of Thread class:

 public void run(): is used to perform action for a thread.

 public void start(): starts the execution of the thread.JVM calls the run()

method on the thread.

 public void sleep(long miliseconds): Causes the currently executing

thread to sleep (temporarily cease execution) for the specified number of

[email protected]
Ph: 9014424466 Page 9
TechVeerendra’s
Software Solutions

milliseconds.

 public void join(): waits for a thread to die.

 public void join(long miliseconds): waits for a thread to die for the

specified miliseconds.

 public int getPriority(): returns the priority of the thread.

 public int setPriority(int priority): changes the priority of the thread.

 public String getName(): returns the name of the thread.

 public void setName(String name): changes the name of the thread.

 public Thread currentThread(): returns the reference of currently

executing thread.

 public int getId(): returns the id of the thread.

 public Thread.State getState(): returns the state of the thread.

 public boolean isAlive(): tests if the thread is alive.

 public void yield(): causes the currently executing thread object to

temporarily pause and allow other threads to execute.

 public void suspend(): is used to suspend the thread(depricated).

 public void resume(): is used to resume the suspended

thread(depricated).

 public void stop(): is used to stop the thread(depricated).

 public boolean isDaemon(): tests if the thread is a daemon thread.

 public void setDaemon(boolean b): marks the thread as daemon or user

[email protected]
Ph: 9014424466 Page 10
TechVeerendra’s
Software Solutions

thread.

 public void interrupt(): interrupts the thread.

 public boolean isInterrupted(): tests if the thread has been interrupted.

 public static boolean interrupted(): tests if the current thread has been

interrupted.

Runnable interface:

The Runnable interface should be implemented by any class whose instances


are intended to be executed by a thread. Runnable interface have only one
method named run().

public void run(): is used to perform action for a thread.

Starting a thread:

start() method of Thread class is used to start a newly created thread. It


performs following tasks:

o A new thread starts(with new call stack).

o The thread moves from New state to the Runnable state.

o When the thread gets a chance to execute, its target run() method will
run.

1) Java Thread Example by extending Thread class:

class Multi extends Thread{  

public void run(){  

System.out.println("thread is running...");  

[email protected]
Ph: 9014424466 Page 11
TechVeerendra’s
Software Solutions

}  

public static void main(String args[]){  

Multi t1=new Multi();  

t1.start();  

 }  

}  

Output: thread is running...

2) Java Thread Example by implementing Runnable interface:

class Multi implements Runnable{  

public void run(){  

System.out.println("thread is running...");  

}  

public static void main(String args[]){  

Multi m1=new Multi();  

Thread t1 =new Thread(m1);  

t1.start();  

 }  

}  

Output: thread is running...

Note: If you are not extending the Thread class, your class object would not
be treated as a thread object.So you need to explicitely create Thread class
object.

We are passing the object of our class that implements Runnable so that our
class run() method may execute.

[email protected]
Ph: 9014424466 Page 12
TechVeerendra’s
Software Solutions

Defining a Thread by extending "Thread class":

Example: MyThread.java

ThreadDemo.java

[email protected]
Ph: 9014424466 Page 13
TechVeerendra’s
Software Solutions

class ThreadDemo

public static void main(String[] args)

MyThread t1=new MyThread();//Instantiation of a Thread

t1.start();//starting of a Thread

for(int i=0;i<5;i++)

System.out.println("main thread");

In the above program, MyThread class extends Thread. To create a thread in


Java, just extend Thread class and create an object, the object becomes a
thread implicitly. Now, t1 is a thread of MyThread class. Actually, t1 is an
object of Demo class but we are calling it as a thread (because Demo extends
Thread). This is how Java makes thread manipulation easy to the programmer;

The thread, t1, is created, occupies some memory, but still it is inactive. An


inactive thread is not eligible for microprocessor time even if the processor is
idle. To make the thread active, call start() method on the thread.
Now, t1 becomes active and eligible for a time-slice. start()is a method of
Thread class. Forgetting to call the start() method makes the thread to die in
inactive state itself without performing the job assigned.

Whenever the thread is started, the first and foremost job it does is calling
the run() method. It is a predefined thread of Thread class. This method is the

[email protected]
Ph: 9014424466 Page 14
TechVeerendra’s
Software Solutions

heart of the thread and whatever code is expected to run by the thread should
be put here. When the execution of run() method is over, the thread dies
implicitly; naturally, its job is over.

Thread Scheduler in Java

If multiple Threads are waiting to execute then which Thread will execute 1st is
decided by "Thread Scheduler" which is part of JVM.

Which algorithm or behavior followed by Thread Scheduler we can't expect


exactly it is the JVM vendor dependent hence in multithreading examples we
can't expect exact execution order and exact output.

Only one thread at a time can run in a single process.

The thread scheduler mainly uses preemptive or time slicing scheduling to


schedule the threads.

Difference between preemptive scheduling and time slicing:

Under preemptive scheduling, the highest priority task executes until it enters
the waiting or dead states or a higher priority task comes into existence. Under
time slicing, a task executes for a predefined slice of time and then reenters the
pool of ready tasks. The scheduler then determines which task should execute
next, based on priority and other factors.

The following are various possible outputs for the above program.

[email protected]
Ph: 9014424466 Page 15
TechVeerendra’s
Software Solutions

Case 2: Difference between t.start() and t.run() methods:

In the case of t.start() a new Thread will be created which is responsible for the
execution of run() method.

But in the case of t.run() no new Thread will be created and run() method will
be executed just like a normal method by the main Thread.

In the above program if we are replacing t.start() with t.run() the following is the
output.

ThreadDemo.java

class ThreadDemo

[email protected]
Ph: 9014424466 Page 16
TechVeerendra’s
Software Solutions

public static void main(String[] args)

MyThread t1=new MyThread();//Instantiation of a Thread

t1.run();//no Thread creation

for(int i=0;i<5;i++)

System.out.println("main thread");

Output:

child thread

child thread

child thread

child thread

child thread

child thread

child thread

child thread

child thread

[email protected]
Ph: 9014424466 Page 17
TechVeerendra’s
Software Solutions

child thread

main thread

main thread

main thread

main thread

main thread

Note: Entire output produced by only main Thread.

Case 3: importance of Thread class start() method.

For every Thread the required mandatory activities like registering the Thread
with Thread Scheduler will takes care by Thread class start() method and
programmer is responsible just to define the job of the Thread inside run()
method.

That is start() method acts as best assistant to the programmer.

Example:

start()

1. Register Thread with Thread Scheduler

2. All other mandatory low level activities.

3. Invoke or calling run() method.

[email protected]
Ph: 9014424466 Page 18
TechVeerendra’s
Software Solutions

Note: We can conclude that without executing Thread class start() method
there is no chance of starting a new Thread in java. Due to this start() is
considered as heart of multithreading.

Case 4: If we are not overriding run() method:

If we are not overriding run() method then Thread class run() method will be
executed which has empty implementation and hence we won't get any output.

Example:

class MyThread extends Thread

class ThreadDemo

public static void main(String[] args)

MyThread t=new MyThread();

t.start();

It is highly recommended to override run() method. Otherwise don't go for


multithreading concept.

Case 5: Overloding of run() method.

We can overload run() method but Thread class start() method always invokes
no argument run() method the other overload run() methods we have to call
explicitly then only it will be executed just like normal method.

[email protected]
Ph: 9014424466 Page 19
TechVeerendra’s
Software Solutions

Example:

class MyThread extends Thread

public void run()

System.out.println("no arg method");

public void run(int i)

System.out.println("int arg method");

ThreadDemo.java

class ThreadDemo

public static void main(String[] args)

MyThread t=new MyThread();

t.start();

Output:

No arg method

Case 6: overriding of start() method:

[email protected]
Ph: 9014424466 Page 20
TechVeerendra’s
Software Solutions

If we override start() method then our start() method will be executed just like a
normal method call and no new Thread will be started.

Example:

class MyThread extends Thread

public void start()

System.out.println("start method");

public void run()

System.out.println("run method");

class ThreadDemo

public static void main(String[] args)

MyThread t=new MyThread();

t.start();

System.out.println("main method");

Output:

start method

[email protected]
Ph: 9014424466 Page 21
TechVeerendra’s
Software Solutions

main method

Note: Entire output produced by only main Thread.

Note: It is never recommended to override start() method.

Case 7:

Output:

Case 8: life cycle of the Thread (Thread States):

A thread can be in one of the five states. According to sun, there is only 4
states in thread life cycle in java new, runnable, non-runnable and terminated.
There is no running state.

But for better understanding the threads, we are explaining it in the 5 states.

[email protected]
Ph: 9014424466 Page 22
TechVeerendra’s
Software Solutions

The life cycle of the thread in java is controlled by JVM. The java thread states
are as follows:

1. New/Born

2. Ready/Runnable

3. Running

4. Non-Runnable (Blocked)

5. Dead/Terminated

Diagram:

1) New/born:

The thread is in new state if you create an instance of Thread class but before
the invocation of start() method.

In born state, the thread object is created, occupies memory but is inactive. In
the above statement t1 thread is created but is not eligible for microprocessor
time as it is inactive.

To make the thread active, call start() method on the thread object as t1.start().


This makes the thread active and now eligible for processor time slices.

2) Ready/Runnable:

The thread is in runnable state after invocation of start() method, but the
thread scheduler has not selected it to be the running thread.

[email protected]
Ph: 9014424466 Page 23
TechVeerendra’s
Software Solutions

3) Running:

The thread is in running state if the thread scheduler has selected it.

4) Non-Runnable (Blocked):

This is the state when the thread is still alive, but is currently not eligible to
run.

5) Terminated/Dead:

A thread is in terminated or dead state when its run() method exits.

Concusion:

 Once we created a Thread object then the Thread is said to be in new


state or born state.
 Once we call start() method then the Thread will be entered into Ready or
Runnable state.
 If Thread Scheduler allocates CPU then the Thread will be entered into
running state.
 Once run() method completes then the Thread will entered into dead
state.

Case 9:

After starting a Thread we are not allowed to restart the same Thread once
again otherwise we will get runtime exception saying
"IllegalThreadStateException".

Example:

MyThread t=new MyThread();

t.start();//valid

[email protected]
Ph: 9014424466 Page 24
TechVeerendra’s
Software Solutions

;;;;;;;;

t.start();//we will get R.E saying: IllegalThreadStateException

Defining a Thread by implementing Runnable interface:

We can define a Thread even by implementing Runnable interface also.

Runnable interface present in java.lang.pkg and contains only one method


run().

Example:

[email protected]
Ph: 9014424466 Page 25
TechVeerendra’s
Software Solutions

class ThreadDemo

public static void main(String[] args)

MyRunnable r=new MyRunnable();

Thread t=new Thread(r);//here r is a Target Runnable

t.start();

for(int i=0;i<10;i++)

System.out.println("main thread");

Output:
[email protected]
Ph: 9014424466 Page 26
TechVeerendra’s
Software Solutions

main thread

main thread

main thread

main thread

main thread

main thread

main thread

main thread

main thread

main thread

child Thread

child Thread

child Thread

child Thread

child Thread

child Thread

child Thread

child Thread

child Thread

child Thread

Note: We can't expect exact output but there are several possible outputs.

[email protected]
Ph: 9014424466 Page 27
TechVeerendra’s
Software Solutions

Case study:

MyRunnable r=new MyRunnable();

Thread t1=new Thread();

Thread t2=new Thread(r);

Case 1: t1.start():

A new Thread will be created which is responsible for the execution of Thread
class run()method.

Output:

main thread

main thread

main thread

main thread

main thread

Case 2: t1.run():

No new Thread will be created but Thread class run() method will be executed
just like a normal method call.

Output:

main thread

main thread

main thread

main thread

main thread

Case 3: t2.start():

[email protected]
Ph: 9014424466 Page 28
TechVeerendra’s
Software Solutions

New Thread will be created which is responsible for the execution of


MyRunnable run() method.

Output:

main thread

main thread

main thread

main thread

main thread

child Thread

child Thread

child Thread

child Thread

child Thread

Case 4: t2.run():

No new Thread will be created and MyRunnable run() method will be executed
just like a normal method call.

Output:

child Thread

child Thread

child Thread

child Thread

child Thread

main thread

main thread

[email protected]
Ph: 9014424466 Page 29
TechVeerendra’s
Software Solutions

main thread

main thread

main thread

Case 5: r.start():

We will get compile time error saying start()method is not available in


MyRunnable class.

Output:

Compile time error

E:\SCJP>javac ThreadDemo.java

ThreadDemo.java:18: cannot find symbol

Symbol: method start()

Location: class MyRunnable

Case 6: r.run():

No new Thread will be created and MyRunnable class run() method will be
executed just like a normal method call.

Output:

child Thread

child Thread

child Thread

child Thread

child Thread

main thread

[email protected]
Ph: 9014424466 Page 30
TechVeerendra’s
Software Solutions

main thread

main thread

main thread

main thread

In which of the above cases a new Thread will be created which is responsible
for the execution of MyRunnable run() method ?

t2.start();

In which of the above cases a new Thread will be created ?

t1.start();

t2.start();

In which of the above cases MyRunnable class run() will be executed ?

t2.start();

t2.run();

r.run();

[email protected]
Ph: 9014424466 Page 31
TechVeerendra’s
Software Solutions

Output:

main method
run method

Best approach to define a Thread:

 Among the 2 ways of defining a Thread, implements Runnable approach


is always recommended.
 In the 1st approach our class should always extends Thread class there
is no chance of extending any other class hence we are missing the
benefits of inheritance.
 But in the 2nd approach while implementing Runnable interface we can
extend some other class also. Hence implements Runnable mechanism is
recommended to define a Thread.

Thread class constructors:

1. Thread t=new Thread();

2. Thread t=new Thread(Runnable r);

3. Thread t=new Thread(String name);

4. Thread t=new Thread(Runnable r,String name);

[email protected]
Ph: 9014424466 Page 32
TechVeerendra’s
Software Solutions

5. Thread t=new Thread(ThreadGroup g,String name);

6. Thread t=new Thread(ThreadGroup g,Runnable r);

7. Thread t=new Thread(ThreadGroup g,Runnable r,String name);

8. Thread t=new Thread(ThreadGroup g,Runnable r,String name,long


stackSize);

Single tasking using a Thread:

Ex: showing multiple tasks with a single thread.

//single tasking using a thread.

class Mythread implements Runnable{

public void run(){

//execute the tasks one by one by calling the methods

task1();

task2();

task3();

public void task1(){

System.out.println(“Task1 completed”);

public void task2(){

System.out.println(“Task2 completed”);

public void task3(){

System.out.println(“Task3 completed”);

[email protected]
Ph: 9014424466 Page 33
TechVeerendra’s
Software Solutions

class Test{

public static void main(String[] args){

//creat object for MyThread

MyThread obj=new MyThread();

//creat a Thread t1 and attech it to that obj

Thread t1=new Thread(obj);

t1.run();

Multi Tasking using Thread:

Ex: show two Threads working simultaneously upon two objects.

class MyThread implements Runnable{

String atr;

MyThread(String atr){

this.str=str;

public void run(){

for(int i=1;i<=10;i++){

System.out.println(str”:”+i);

try{

Thread.sleep(2000);

}catch(InterruptedException e){

e.printStackTrace();

[email protected]
Ph: 9014424466 Page 34
TechVeerendra’s
Software Solutions

class Theatre{

public static void main(String[] args){

MyThread m1=new MyThread();

MyThread m2=new MyThread();

m1.run();

m2.run();

Multiple Thread acting on single Object:

class Reserve implements Runnable{

//available berth are 1

int available =1;

int wanted;

Reserve(int i){

Wanted=i;

public void run(){

//display available beths

System.out.println(“available berths are”+available);

//if available berths are more than wanted

if(available>=wanted){

//get name of the passenger

String name =Thread.currentThread.getName();

System.out.println(wanted+”berths reserved for”+name);

[email protected]
Ph: 9014424466 Page 35
TechVeerendra’s
Software Solutions

try{

Thread.sleep(2000);//time to print

available =available – wanted;//update

}catch(InterruptedException ie){

else{

System.out.println(“sorry no berths”);

class Test{

public static void main(String[] args){

//need 1 berth

Reserve obj=new Reserve(1);

Thread t1=new Thread(obj);

Thread t2=new Thread(obj);

t1.start();

t2.start();

[email protected]
Ph: 9014424466 Page 36
TechVeerendra’s
Software Solutions

Getting and setting name of a Thread


 Every Thread in java has some name it may be provided explicitly by the
programmer or automatically generated by JVM.
 The Thread class provides methods to change and get the name of a
thread. By default, each thread has a name i.e. thread-0, thread-1 and
so on.
 Thread class defines the following methods to get and set name of a
Thread.

Methods:

1. public final String getName()

2. public final void setName(String name)

Ex:

class TestMultiNaming1 extends Thread{  

  public void run(){  

   System.out.println("running...");  

  }  

 public static void main(String args[]){ 

System.out.println(Thread.currentThread().getName());//main 

  TestMultiNaming1 t1=new TestMultiNaming1();  

  TestMultiNaming1 t2=new TestMultiNaming1();  

  System.out.println("Name of t1:"+t1.getName()); //Thtread-0 

  System.out.println("Name of t2:"+t2.getName());  
[email protected]
Ph: 9014424466 Page 37
TechVeerendra’s
Software Solutions

   

  t1.start();  

  t2.start();  

  

  t1.setName("Veerendra");  

 // System.out.println("After changing name of t1:"+t1.getName());

System.out.println(Thread.currentThread().getName());  

 }  

}  

Note: We can get current executing Thread object reference by using

Thread.currentThread() method.

Current Thread:

The currentThread() method returns a reference of currently executing thread.

public static Thread currentThread()  

Example:

class TestMultiNaming2 extends Thread{  

 public void run(){  

  System.out.println(“Inside Child”+Thread.currentThread().getName());  

 }  

 public static void main(String args[]){  

  TestMultiNaming2 t1=new TestMultiNaming2();  

  TestMultiNaming2 t2=new TestMultiNaming2();  

  
[email protected]
Ph: 9014424466 Page 38
TechVeerendra’s
Software Solutions

  t1.start();  

  t2.start();  

 }  

}  

Priority of a Thread (Thread Priority):


 Every Thread in java has some priority it may be default priority
generated by JVM (or) explicitly provided by the programmer.
 The valid range of Thread priorities is 1 to 10[but not 0 to 10] where 1 is
the least priority and 10 is highest priority.
 Thread class defines the following constants to represent some standard
priorities.
3 constants defined in Thread class:
1. public static int MIN_PRIORITY
2. public static int NORM_PRIORITY
3. public static int MAX_PRIORITY
 Default priority of a thread is 5 (NORM_PRIORITY). The value of
MIN_PRIORITY is 1 and the value of MAX_PRIORITY is 10.
 There are no constants like Thread.LOW_PRIORITY,
Thread.HIGH_PRIORITY
 Thread scheduler uses these priorities while allocating CPU.
 The Thread which is having highest priority will get chance for 1st
execution.
 If 2 Threads having the same priority then we can't expect exact
execution order it depends on Thread scheduler whose behavior is vendor
dependent.
 We can get and set the priority of a Thread by using the following
methods.

[email protected]
Ph: 9014424466 Page 39
TechVeerendra’s
Software Solutions

1. public final int getPriority()


2. public final void setPriority(int newPriority);//the allowed values are 1 to 10

Note: The allowed values are 1 to 10 otherwise we will get runtime exception

saying "IllegalArgumentException".

Ex:
class TestMultiPriority1 extends Thread{  
 public void run(){  
   System.out.println("running thread name is:"+Thread.currentThread().get
Name());  
   System.out.println("running thread priority is:"+Thread.currentThread().ge
tPriority());  
  
  }  
 public static void main(String args[]){  
  TestMultiPriority1 m1=new TestMultiPriority1();  
  TestMultiPriority1 m2=new TestMultiPriority1();  
  m1.setPriority(Thread.MIN_PRIORITY);  
  m2.setPriority(Thread.MAX_PRIORITY);  
  m1.start();  
  m2.start();  
   
 }  
}     
Output: running thread name is:Thread-0
running thread priority is:10
running thread name is:Thread-1
running thread priority is:1

[email protected]
Ph: 9014424466 Page 40
TechVeerendra’s
Software Solutions

Default priority:
The default priority only for the main Thread is 5. But for all the remaining
Threads the default priority will be inheriting from parent to child. That is
whatever the priority parent has by default the same priority will be for the
child also.
Example 1:
class MyThread extends Thread
{}
class ThreadPriorityDemo
{
public static void main(String[] args)
{
System.out.println(Thread.currentThread().getPriority());//5
Thread.currentThread().setPriority(9);
MyThread t=new MyThread();
System.out.println(t.getPriority());//9
}
}
Example 2:
class MyThread extends Thread
{
public void run()
{
for(int i=0;i<10;i++)
{
System.out.println("child thread");
}
}

[email protected]
Ph: 9014424466 Page 41
TechVeerendra’s
Software Solutions

}
class ThreadPriorityDemo
{
public static void main(String[] args)
{
MyThread t=new MyThread();
//t.setPriority(10); //----> 1
t.start();
for(int i=0;i<10;i++)
{
System.out.println("main thread");
}
}
}
 If we are commenting line 1 then both main and child Threads will have
the same priority and hence we can't expect exact execution order.
 If we are not commenting line 1 then child Thread has the priority 10 and
main Thread has the priority 5 hence child Thread will get chance for
execution and after completing child Thread main Thread will get the
chance in this the output is:
Output:

child thread
child thread
child thread
child thread
child thread
child thread
child thread

[email protected]
Ph: 9014424466 Page 42
TechVeerendra’s
Software Solutions

child thread
child thread
child thread
main thread
main thread
main thread
main thread
main thread
main thread
main thread
main thread
main thread
main thread
Some operating systems(like windowsXP) may not provide proper support for
Thread priorities. We have to install separate bats provided by vendor to provide
support for priorities.

The Methods to Prevent a Thread from Execution:


We can prevent(stop) a Thread execution by using the following methods.
1. yield();
2. join();
3. sleep();

yield():
1. yield() method causes "to pause current executing Thread for giving the

chance of remaining waiting Threads of same priority".

2. If all waiting Threads have the low priority or if there is no waiting Threads

[email protected]
Ph: 9014424466 Page 43
TechVeerendra’s
Software Solutions

then the same Thread will be continued its execution.

3. If several waiting Threads with same priority available then we can't expect

exact which Thread will get chance for execution.

4. The Thread which is yielded when it get chance once again for execution is

depends on mercy of the Thread scheduler.

5. public static native void yield();

EX:

class MyThread extends Thread

public void run()

for(int i=0;i<5;i++)

Thread.yield();

System.out.println("child thread");

class ThreadYieldDemo

[email protected]
Ph: 9014424466 Page 44
TechVeerendra’s
Software Solutions

public static void main(String[] args)

MyThread t=new MyThread();

t.start();

for(int i=0;i<5;i++)

System.out.println("main thread");

Output:

main thread

main thread

main thread

main thread

main thread

child thread

child thread

child thread

child thread

child thread

[email protected]
Ph: 9014424466 Page 45
TechVeerendra’s
Software Solutions

In the above program child Thread always calling yield() method and hence
main Thread will get the chance more number of times for execution.

Hence the chance of completing the main Thread first is high.

Note: Some operating systems may not provide proper support for yield()
method.

Join():

If a Thread wants to wait until completing some other Thread then we should
go for join() method.

Example: If a Thread t1 executes t2.join() then t1 should go for waiting state


until completing t2.

1. public final void join()throws InterruptedException

2. public final void join(long ms) throws InterruptedException

3. public final void join(long ms,int ns) throws InterruptedException

[email protected]
Ph: 9014424466 Page 46
TechVeerendra’s
Software Solutions

Every join() method throws InterruptedException, which is checked exception


hence compulsory we should handle either by try catch or by throws keyword.

Otherwise we will get compiletime error.

Example:

class MyThread extends Thread

public void run()

for(int i=0;i<5;i++)

System.out.println("Sita Thread");

try

Thread.sleep(2000);

catch (InterruptedException e){}

[email protected]
Ph: 9014424466 Page 47
TechVeerendra’s
Software Solutions

class ThreadJoinDemo

public static void main(String[] args)throws InterruptedException

MyThread t=new MyThread();

t.start();

//t.join(); //--->1

for(int i=0;i<5;i++)

System.out.println("Rama Thread");

 If we are commenting line 1 then both Threads will be executed


simultaneously and we can't expect exact execution order.
 If we are not commenting line 1 then main Thread will wait until
completing child Thread in this the output is sita Thread 5 times followed
by Rama Thread 5 times.

Waiting of main() Thread until Child Thread completion:

class MyTread extends Thread{

public void run(){

for(int i=0;i<10;i++){

System.out.println(“Kajal Thread”);

[email protected]
Ph: 9014424466 Page 48
TechVeerendra’s
Software Solutions

try{

Thread.sleep(2000);

}catch(InterruptedException ie){

Class ThreadJoinDemo{

Public static void main(String[] args){

MyThread t=new MyThread();

t.start();

t.join();//---line-1 main thread waiting

for(int i=0;i<10;i++){

System.out.println(“Pawan Thread”);

If we are not commenting line-1 then main Thread executes join() method on
child thread object.

Hence main() thread has to wait until completing child thread object

[email protected]
Ph: 9014424466 Page 49
TechVeerendra’s
Software Solutions

Output:

Kajal thread

Kajal thread

-------(10 times)

Pawan thread

Pawan thread

-------------(10 times)

If we are commenting line-1 then we can’t expect exact execution order and
exact output.

Note: Every join() method throws InterruptedException which is checked


Exception and hence whenever we are using join() method compulsory we
should handle InterruptedException either by try-catch or throws keyword
otherwise we will get Copiletime error.

Waiting of child Thread untill completing main Thread :

Example:

class MyThread extends Thread

static Thread mt;

public void run()

try

mt.join();

[email protected]
Ph: 9014424466 Page 50
TechVeerendra’s
Software Solutions

catch (InterruptedException e){}

for(int i=0;i<5;i++)

System.out.println("Child Thread");

class ThreadJoinDemo

public static void main(String[] args)throws InterruptedException

MyThread mt=Thread.currentThread();

MyThread t=new MyThread();

t.start();

for(int i=0;i<5;i++)

Thread.sleep(2000);

System.out.println("Main Thread");

Output:

Main Thread

Main Thread

[email protected]
Ph: 9014424466 Page 51
TechVeerendra’s
Software Solutions

Main Thread

Main Thread

Main Thread

Child Thread

Child Thread

Child Thread

Child Thread

Child Thread

Note:

If main thread calls join() on child thread object and child thread called join()
on main thread object then both threads will wait for each other forever and
the program will be hanged(like deadlock if a Thread class join() method on the
same thread itself then the program will be hanged ).

Example :

class ThreadDemo {

public static void main() throws InterruptedException {

Thread.currentThread().join();

--------------- --------

main main

Note: If a thread calls join() method on the same thread object then the
program will be hanged like Deadlock.

Ex: Thread.currentThread.join();

[email protected]
Ph: 9014424466 Page 52
TechVeerendra’s
Software Solutions

In this case thread has to wait infinite of time

class Test{

public static void main(String[] args){

Thread.currentThread.join();

Ex:

class TestJoinMethod1 extends Thread{  

 public void run(){  

  for(int i=1;i<=5;i++){  

   try{  

    Thread.sleep(500);  

   }catch(Exception e){System.out.println(e);}  

  System.out.println(i);  

  }  

 }  

public static void main(String args[]){  

 TestJoinMethod1 t1=new TestJoinMethod1();  

 TestJoinMethod1 t2=new TestJoinMethod1();  

 TestJoinMethod1 t3=new TestJoinMethod1();  

 t1.start();  

 try{  

  t1.join();  

[email protected]
Ph: 9014424466 Page 53
TechVeerendra’s
Software Solutions

 }catch(Exception e){System.out.println(e);}  

  

 t2.start();  

 t3.start();  

 }  

}  

Output:1

[email protected]
Ph: 9014424466 Page 54
TechVeerendra’s
Software Solutions

Ex:

class TestJoinMethod2 extends Thread{  

 public void run(){  

  for(int i=1;i<=5;i++){  

   try{  

    Thread.sleep(500);  

   }catch(Exception e){System.out.println(e);}  

  System.out.println(i);  

  }  

 }  

public static void main(String args[]){  

 TestJoinMethod2 t1=new TestJoinMethod2();  

 TestJoinMethod2 t2=new TestJoinMethod2();  

 TestJoinMethod2 t3=new TestJoinMethod2();  

 t1.start();  

 try{  

  t1.join(1500);  

 }catch(Exception e){System.out.println(e);}  

  

 t2.start();  

 t3.start();  

 }  

}  
[email protected]
Ph: 9014424466 Page 55
TechVeerendra’s
Software Solutions

Output:1

getName(),setName(String) and getId() method:

public String getName()

public void setName(String name)

public long getId()

class TestJoinMethod3 extends Thread{  

  public void run(){  

   System.out.println("running...");  

  }  

 public static void main(String args[]){  

  TestJoinMethod3 t1=new TestJoinMethod3();  

[email protected]
Ph: 9014424466 Page 56
TechVeerendra’s
Software Solutions

  TestJoinMethod3 t2=new TestJoinMethod3();  

  System.out.println("Name of t1:"+t1.getName());  

  System.out.println("Name of t2:"+t2.getName());  

  System.out.println("id of t1:"+t1.getId());  

  

  t1.start();  

  t2.start();  

  

  t1.setName("Sonoo Jaiswal");  

  System.out.println("After changing name of t1:"+t1.getName());  

 }  

}  

Output:Name of t1:Thread-0

Name of t2:Thread-1

id of t1:8

running...

After changling name of t1:Sonoo Jaiswal

running...

[email protected]
Ph: 9014424466 Page 57
TechVeerendra’s
Software Solutions

Sleep() method:

If a Thread don't want to perform any operation for a particular amount of time
then we should go for sleep() method.

1. public static native void sleep(long ms) throws InterruptedException

2. public static void sleep(long ms,int ns)throws InterruptedException

Note: Every sleep() method throws InterruptedException which is checked


Exception hence we should handle InterruptionException either try-catch or
throws keyword otherwise we will get compile time error.

Example:

class ThreadSleepDemo

public static void main(String[] args)throws InterruptedException

[email protected]
Ph: 9014424466 Page 58
TechVeerendra’s
Software Solutions

System.out.println("M");

Thread.sleep(3000);

System.out.println("E");

Thread.sleep(3000);

System.out.println("G");

Thread.sleep(3000);

System.out.println("A");

Output:

Ex-2:

class TestSleepMethod1 extends Thread{  

 public void run(){  

  for(int i=1;i<5;i++){  

    try{

Thread.sleep(500);

}catch(InterruptedException e){

System.out.println(e);

}  

    System.out.println(i);  

  }  

[email protected]
Ph: 9014424466 Page 59
TechVeerendra’s
Software Solutions

 }  

 public static void main(String args[]){  

  TestSleepMethod1 t1=new TestSleepMethod1();  

  TestSleepMethod1 t2=new TestSleepMethod1();  

   

  t1.start();  

  t2.start();  

 }  

}  

Output:

Interrupting a Thread:
How a Thread can interrupt another thread?

If a Thread can interrupt a sleeping or waiting Thread by using interrupt()


(break off) method of Thread class.

public void interrupt();

Example:

class MyThread extends Thread

[email protected]
Ph: 9014424466 Page 60
TechVeerendra’s
Software Solutions

public void run()

try

for(int i=0;i<5;i++)

System.out.println("i am lazy Thread :"+i);

Thread.sleep(2000);

catch (InterruptedException e)

System.out.println("i got interrupted");

class ThreadInterruptDemo

public static void main(String[] args)

MyThread t=new MyThread();

t.start();

//t.interrupt(); //--->1

System.out.println("end of main thread");

[email protected]
Ph: 9014424466 Page 61
TechVeerendra’s
Software Solutions

If we are commenting line 1 then main Thread won't interrupt child Thread and
hence child Thread will be continued until its completion.

If we are not commenting line 1 then main Thread interrupts child Thread and
hence child Thread won't continued until its completion in this case the output
is:

End of main thread

I am lazy Thread: 0

I got interrupted

Note:

 Whenever we are calling interrupt() method we may not see the effect
immediately, if the target Thread is in sleeping or waiting state it will be
interrupted immediately.
 If the target Thread is not in sleeping or waiting state then interrupt call
will wait until target Thread will enter into sleeping or waiting state. Once
target
 Thread entered into sleeping or waiting state it will effect immediately.
 In its lifetime if the target Thread never entered into sleeping or waiting
state then there is no impact of interrupt call simply interrupt call will be
wasted.

Example:

class MyThread extends Thread

[email protected]
Ph: 9014424466 Page 62
TechVeerendra’s
Software Solutions

public void run()

for(int i=0;i<5;i++)

System.out.println("iam lazy thread");

System.out.println("I'm entered into sleeping stage");

try

Thread.sleep(3000);

catch (InterruptedException e)

System.out.println("i got interrupted");

class ThreadInterruptDemo1

public static void main(String[] args)

MyThread t=new MyThread();

t.start();

System.out.println("end of main thread");

[email protected]
Ph: 9014424466 Page 63
TechVeerendra’s
Software Solutions

In the above program interrupt() method call invoked by main Thread will wait
until child Thread entered into sleeping state.

Once child Thread entered into sleeping state then it will be interrupted
immediately.

Differences between yield() and sleep():

1. It differs from sleep() in that sleep() takes a long parameter and yield()
carries no parameter.

2. yield time is not in the hands of Programmer where as sleep() time is.

[email protected]
Ph: 9014424466 Page 64
TechVeerendra’s
Software Solutions

3. It is advised to use sleep() instead of yield() to halt or stop the execution


of a thread for a while. Blocked time is in Programmer’s control with
sleep() method.

4. yield() is given to Programmer to give a chance to other threds to execute.


sleep() is given to stop current thread execution.

5. yield() method voluntarily gives up (or stops temporarily) the execution of


the current thread giving chance to other threads waiting for processor’s
time. If no other threads are waiting or other threads have lower priority,
the execution proceeds with the same thread. But sleep() method stops
the execution for the specified time eventhough no other waiting threads
exist.

6. sleep() suspends the execution for a specified number of milliseconds


where as yield() makes the thread to join the pool of waiting threads (or
joins the queue of waiting threads at the last).

Synchronization in Java

Synchronization in java is the capability to control the access of multiple


threads to any shared resource.

Java Synchronization is better option where we want to allow only one thread
to access the shared resource.

1. Synchronized is the keyword applicable for methods and blocks but not for
classes and variables.

2. If a method or block declared as the synchronized then at a time only one


Thread is allow to execute that method or block on the given object.

3. The main advantage of synchronized keyword is we can resolve date


inconsistency problems.

[email protected]
Ph: 9014424466 Page 65
TechVeerendra’s
Software Solutions

4. But the main disadvantage of synchronized keyword is it increases waiting


time of the Thread and effects performance of the system.

5. Hence if there is no specific requirement then never recommended to use


synchronized keyword.

6. Internally synchronization concept is implemented by using lock concept.

7. Every object in java has a unique lock. Whenever we are using synchronized
keyword then only lock concept will come into the picture.

8. If a Thread wants to execute any synchronized method on the given object


1st it has to get the lock of that object. Once a Thread got the lock of that
object then it's allow to execute any synchronized method on that object. If the
synchronized method execution completes then automatically Thread releases
lock.

9. While a Thread executing any synchronized method the remaining Threads


are not allowed execute any synchronized method on that object
simultaneously. But remaining Threads are allowed to execute any non-
synchronized method simultaneously. [lock concept is implemented based on
object but not based on method].

Why use Synchronization

The synchronization is mainly used to

1. To prevent thread interference.

2. To prevent consistency problem.

[email protected]
Ph: 9014424466 Page 66
TechVeerendra’s
Software Solutions

Types of Synchronization

There are two types of synchronization

1. Process Synchronization

2. Thread Synchronization

Here, we will discuss only thread synchronization.

Thread Synchronization:

There are two types of thread synchronization mutual exclusive and inter-
thread communication.

1. Mutual Exclusive

1. Synchronized method.

2. Synchronized block.

3. static synchronization.

2. Cooperation (Inter-thread communication in java)

Mutual Exclusive

Mutual Exclusive helps keep threads from interfering with one another while
sharing data. This can be done by three ways in java:

1. by synchronized method

2. by synchronized block

3. by static synchronization

[email protected]
Ph: 9014424466 Page 67
TechVeerendra’s
Software Solutions

Understanding the problem without Synchronization

class Table{  

void printTable(int n){//method not synchronized  

   for(int i=1;i<=5;i++){  

     System.out.println(n*i);  

     try{  

      Thread.sleep(400);  

     }catch(Exception e){System.out.println(e);}  

   }  

  

 }  

}  

class MyThread1 extends Thread{  

Table t;  

MyThread1(Table t){  

this.t=t;  

}  

public void run(){  

t.printTable(5);  

}  

}  

[email protected]
Ph: 9014424466 Page 68
TechVeerendra’s
Software Solutions

class MyThread2 extends Thread{  

Table t;  

MyThread2(Table t){  

this.t=t;  

}  

public void run(){  

t.printTable(100);  

}  

}  

class TestSynchronization1{  

public static void main(String args[]){  

Table obj = new Table();//only one object  

MyThread1 t1=new MyThread1(obj);  

MyThread2 t2=new MyThread2(obj);  

t1.start();  

t2.start();  

}  

}  

Output: 5

100

10

200

15

[email protected]
Ph: 9014424466 Page 69
TechVeerendra’s
Software Solutions

300

20

400

25

500

Ex

class Display

public synchronized void wish(String name)

for(int i=0;i<5;i++)

System.out.print("good morning:");

try

Thread.sleep(1000);

catch (InterruptedException e)

{}

System.out.println(name);

class MyThread extends Thread

[email protected]
Ph: 9014424466 Page 70
TechVeerendra’s
Software Solutions

Display d;

String name;

MyThread(Display d,String name)

this.d=d;

this.name=name;

public void run()

d.wish(name);

class SynchronizedDemo

public static void main(String[] args)

Display d1=new Display();

MyThread t1=new MyThread(d1,"dhoni");

MyThread t2=new MyThread(d1,"yuvaraj");

t1.start();

t2.start();

If we are not declaring wish() method as synchronized then both Threads will
beexecuted simultaneously and we will get irregular output.

[email protected]
Ph: 9014424466 Page 71
TechVeerendra’s
Software Solutions

Output:

good morning:good morning:yuvaraj

good morning:dhoni

good morning:yuvaraj

good morning:dhoni

good morning:yuvaraj

good morning:dhoni

good morning:yuvaraj

good morning:dhoni

good morning:yuvaraj

dhoni

If we declare wish()method as synchronized then the Threads will be executed


one by one that is until completing the 1st Thread the 2nd Thread will wait in
this case we will get regular output which is nothing but

Output:

good morning:dhoni

good morning:dhoni

good morning:dhoni

good morning:dhoni

good morning:dhoni

good morning:yuvaraj

good morning:yuvaraj

good morning:yuvaraj

good morning:yuvaraj

[email protected]
Ph: 9014424466 Page 72
TechVeerendra’s
Software Solutions

good morning:yuvaraj

Java synchronized method

If you declare any method as synchronized, it is known as synchronized


method.

Synchronized method is used to lock an object for any shared resource.

When a thread invokes a synchronized method, it automatically acquires the


lock for that object and releases it when the thread completes its task.

//example of java synchronized method  

class Table{  

 synchronized void printTable(int n){//synchronized method  

   for(int i=1;i<=5;i++){  

     System.out.println(n*i);  

     try{  

      Thread.sleep(400);  

     }catch(Exception e){System.out.println(e);}  

   }  

  

 }  

}  

  

class MyThread1 extends Thread{  

Table t;  

MyThread1(Table t){  

[email protected]
Ph: 9014424466 Page 73
TechVeerendra’s
Software Solutions

this.t=t;  

}  

public void run(){  

t.printTable(5);  

}  

  

}  

class MyThread2 extends Thread{  

Table t;  

MyThread2(Table t){  

this.t=t;  

}  

public void run(){  

t.printTable(100);  

}  

}  

  

public class TestSynchronization2{  

public static void main(String args[]){  

Table obj = new Table();//only one object  

MyThread1 t1=new MyThread1(obj);  

MyThread2 t2=new MyThread2(obj);  

t1.start();  

[email protected]
Ph: 9014424466 Page 74
TechVeerendra’s
Software Solutions

t2.start();  

}  

}  

Output: 5

10

15

20

25

100

200

300

400

500

Case study:

Case 1:

Display d1=new Display();

Display d2=new Display();

MyThread t1=new MyThread(d1,"dhoni");

MyThread t2=new MyThread(d2,"yuvaraj");

t1.start();

t2.start();

[email protected]
Ph: 9014424466 Page 75
TechVeerendra’s
Software Solutions

Diagram:

Even though we declared wish() method as synchronized but we will get


irregular output in this case, because both Threads are operating on different
objects.

Conclusion : If multiple threads are operating on multiple objects then there is


no impact of Syncronization.

If multiple threads are operating on same java objects then syncronized


concept is required(applicable).

Class level lock:

1. Every class in java has a unique lock. If a Thread wants to execute a static
synchronized method then it required class level lock.

2. Once a Thread got class level lock then it is allow to execute any static
synchronized method of that class.

3. While a Thread executing any static synchronized method the remaining


Threads are not allow to execute any static synchronized method of that class
simultaneously.

[email protected]
Ph: 9014424466 Page 76
TechVeerendra’s
Software Solutions

4. But remaining Threads are allowed to execute normal synchronized


methods, normal static methods, and normal instance methods
simultaneously.

5. Class level lock and object lock both are different and there is no
relationship between these two.

Synchronized block:

1. If very few lines of the code required synchronization then it's never
recommended to declare entire method as synchronized we have to enclose
those few lines of the code with in synchronized block.

2. The main advantage of synchronized block over synchronized method is it


reduces waiting time of Thread and improves performance of the system.

Points to remember for Synchronized block

o Synchronized block is used to lock an object for any shared resource.

o Scope of synchronized block is smaller than the method.

Example:
Program of synchronized block

class Table{  

  

 void printTable(int n){  

   synchronized(this){//synchronized block  

     for(int i=1;i<=5;i++){  

      System.out.println(n*i);  

      try{  

[email protected]
Ph: 9014424466 Page 77
TechVeerendra’s
Software Solutions

       Thread.sleep(400);  

      }catch(Exception e){System.out.println(e);}  

     }  

   }  

 }//end of the method  

}  

  

class MyThread1 extends Thread{  

Table t;  

MyThread1(Table t){  

this.t=t;  

}  

public void run(){  

t.printTable(5);  

}  

  

}  

class MyThread2 extends Thread{  

Table t;  

MyThread2(Table t){  

this.t=t;  

}  

public void run(){  

[email protected]
Ph: 9014424466 Page 78
TechVeerendra’s
Software Solutions

t.printTable(100);  

}  

}  

  

public class TestSynchronizedBlock1{  

public static void main(String args[]){  

Table obj = new Table();//only one object  

MyThread1 t1=new MyThread1(obj);  

MyThread2 t2=new MyThread2(obj);  

t1.start();  

t2.start();  

}  

}  

Output:5

10

15

20

25

100

200

300

400

500

[email protected]
Ph: 9014424466 Page 79
TechVeerendra’s
Software Solutions

Example 1: To get lock of current object we can declare synchronized block as


follows.

If Thread got lock of current object then only it is allowed to execute this block.

Synchronized(this){

Example 2: To get the lock of a particular object 'b' we have to declare a


synchronized block as follows.

If thread got lock of 'b' object then only it is allowed to execute this block.

Synchronized(b){

Example 3: To get class level lock we have to declare synchronized block as


follows.

Synchronized(Display.class){

If thread got class level lock of Display then only it allowed to execute this
block.

Note: As the argument to the synchronized block we can pass either object
reference or

".class file" and we can't pass primitive values as argument [because lock
concept is only for objects and classes but not for primitives].

Example:

int x=b;

[email protected]
Ph: 9014424466 Page 80
TechVeerendra’s
Software Solutions

Synchronized(x){}

Output:

Compile time error.

Unexpected type.

Found: int

Required: reference

What is synchronized statement?

Ans: The statements which present inside synchronized method and


synchronized block are called synchronized statements. [Interview people
created terminology].

Static synchronization

If you make any static method as synchronized, the lock will be on the class
not on object.

[email protected]
Ph: 9014424466 Page 81
TechVeerendra’s
Software Solutions

Problem without static synchronization

Suppose there are two objects of a shared class(e.g. Table) named object1 and
object2.In case of synchronized method and synchronized block there cannot
be interference between t1 and t2 or t3 and t4 because t1 and t2 both refers to
a common object that have a single lock.But there can be interference between
t1 and t3 or t2 and t4 because t1 acquires another lock and t3 acquires
another lock.I want no interference between t1 and t3 or t2 and t4.Static
synchronization solves this problem.

Example of static synchronization

In this example we are applying synchronized keyword on the static method to


perform static synchronization.

class Table{  

  

 synchronized static void printTable(int n){  

   for(int i=1;i<=10;i++){  

     System.out.println(n*i);  

     try{  

       Thread.sleep(400);  

     }catch(Exception e){}  

   }  

 }  

}  

  

class MyThread1 extends Thread{  

public void run(){  

[email protected]
Ph: 9014424466 Page 82
TechVeerendra’s
Software Solutions

Table.printTable(1);  

}  

}  

  

class MyThread2 extends Thread{  

public void run(){  

Table.printTable(10);  

}  

}  

  

class MyThread3 extends Thread{  

public void run(){  

Table.printTable(100);  

}  

}  

  

  

  

  

class MyThread4 extends Thread{  

public void run(){  

Table.printTable(1000);  

}  

}  

  

[email protected]
Ph: 9014424466 Page 83
TechVeerendra’s
Software Solutions

public class TestSynchronization4{  

public static void main(String t[]){  

MyThread1 t1=new MyThread1();  

MyThread2 t2=new MyThread2();  

MyThread3 t3=new MyThread3();  

MyThread4 t4=new MyThread4();  

t1.start();  

t2.start();  

t3.start();  

t4.start();  

}  

}  

Output: 1

10

10

20

30

[email protected]
Ph: 9014424466 Page 84
TechVeerendra’s
Software Solutions

40

50

60

70

80

90

100

100

200

300

400

500

600

700

800

900

1000

1000

2000

3000

4000

5000

6000

7000

8000

[email protected]
Ph: 9014424466 Page 85
TechVeerendra’s
Software Solutions

9000

10000

Inter Thread communication (wait(),notify(), notifyAll()):


 Two Threads can communicate with each other by using wait(), notify()
and notifyAll() methods.
 The Thread which is required updation it has to call wait() method on the
required object then immediately the Thread will entered into waiting
state.
 The Thread which is performing updation of object, it is responsible to
give notification by calling notify() method.
After getting notification the waiting Thread will get those updations.

[email protected]
Ph: 9014424466 Page 86
TechVeerendra’s
Software Solutions

 wait(), notify() and notifyAll() methods are available in Object class but
not in Thread class because Thread can call these methods on any
common object.
 To call wait(), notify() and notifyAll() methods compulsory the current
Thread should be owner of that object i.e., current Thread should has
lock of that object i.e., current Thread should be in synchronized area.
Hence we can call wait(), notify() and notifyAll() methods only from
synchronized area otherwise we willget runtime exception saying
IllegalMonitorStateException.
 Once a Thread calls wait() method on the given object 1st it releases the
lock of that object immediately and entered into waiting state.
 Once a Thread calls notify() (or) notifyAll() methods it releases the lock of
that object but may not immediately.
 Except these (wait(),notify(),notifyAll()) methods there is no other
place(method) where the lock release will be happen.

[email protected]
Ph: 9014424466 Page 87
TechVeerendra’s
Software Solutions

Once a Thread calls wait(), notify(), notifyAll() methods on any object then it
releases the lock of that particular object but not all locks it has.

1. public final void wait()throws InterruptedException

2. public final native void wait(long ms)throws InterruptedException

3. public final void wait(long ms,int ns)throws InterruptedException

4. public final native void notify()

5. public final void notifyAll()

Example 1:

class ThreadA

public static void main(String[] args)throws InterruptedException

ThreadB b=new ThreadB();

b.start();

synchronized(b)

[email protected]
Ph: 9014424466 Page 88
TechVeerendra’s
Software Solutions

System.out.println("main Thread calling wait() method");//step-1

b.wait();

System.out.println("main Thread got notification call");//step-4

System.out.println(b.total);

class ThreadB extends Thread

int total=0;

public void run()

synchronized(this)

System.out.println("child thread starts calcuation");//step-2

for(int i=0;i<=100;i++)

total=total+i;

System.out.println("child thread giving notification call");//step-3

this.notify();

[email protected]
Ph: 9014424466 Page 89
TechVeerendra’s
Software Solutions

Output:

main Thread calling wait() method

child thread starts calculation

child thread giving notification call

main Thread got notification call

5050

Example of inter thread communication in java

class Customer{  

int amount=10000;  

synchronized void withdraw(int amount){  

System.out.println("going to withdraw...");  

if(this.amount<amount){  

System.out.println("Less balance; waiting for deposit...");  

try{wait();}catch(Exception e){}  

}  

this.amount-=amount;  

System.out.println("withdraw completed...");  

}  

synchronized void deposit(int amount){  

[email protected]
Ph: 9014424466 Page 90
TechVeerendra’s
Software Solutions

System.out.println("going to deposit...");  

this.amount+=amount;  

System.out.println("deposit completed... ");  

notify();  

}  

}  

class Test{  

public static void main(String args[]){  

final Customer c=new Customer();  

new Thread(){  

public void run(){c.withdraw(15000);}  

}.start();  

new Thread(){  

public void run(){c.deposit(10000);}  

}.start();  

}}  

Output: going to withdraw...

Less balance; waiting for deposit...

going to deposit...

deposit completed...

withdraw completed

[email protected]
Ph: 9014424466 Page 91
TechVeerendra’s
Software Solutions

Example 2:

Producer consumer problem:

Producer(producer Thread) will produce the items to the queue and


consumer(consumer thread) will consume the items from the queue. If the
queue is empty then consumer has to call wait() method on the queue object
then it will entered into waiting state.

After producing the items producer Thread call notify() method on the queue to
give notification so that consumer Thread will get that notification and
consume items.

Ex:

[email protected]
Ph: 9014424466 Page 92
TechVeerendra’s
Software Solutions

Notify vs notifyAll():

We can use notify() method to give notification for only one Thread. If multiple
Threads are waiting then only one Thread will get the chance and remaining
Threads has to wait for further notification. But which Thread will be
notify(inform) we can't expect exactly it depends on JVM.

We can use notifyAll() method to give the notification for all waiting Threads. All
waiting Threads will be notified and will be executed one by one, because they
are required lock

Note: On which object we are calling wait(), notify() and notifyAll() methods that
corresponding object lock we have to get but not other object locks.

[email protected]
Ph: 9014424466 Page 93
TechVeerendra’s
Software Solutions

Which of the folowing statements are True ?

1. Once a Thread calls wait() on any Object immediately it will entered into
waiting state without releasing the lock ?

NO

2. Once a Thread calls wait() on any Object it reduces the lock of that Object
but not immediately ?

NO

3. Once a Thread calls wait() on any Object it immediately releases all locks
whatever it has and entered into waiting state ?

NO

4. Once a Thread calls wait() on any Object it immediately releases the lock of
that Object and entered into waiting state ?

[email protected]
Ph: 9014424466 Page 94
TechVeerendra’s
Software Solutions

YES

5. Once a Thread calls notify() on any Object it immediately releases the lock of
that Object ?

NO

6. Once a Thread calls notify() on any Object it releases the lock of that Object
but may not immediately ?

YES

Dead lock:

 If 2 Threads are waiting for each other forever(without end) such type of
situation(infinite waiting) is called dead lock.
 There are no resolution techniques for dead lock but several
prevention(avoidance) techniques are possible.
 Synchronized keyword is the cause for deadlock hence whenever we are
using synchronized keyword we have to take special care.

Example of Deadlock in java

public class TestDeadlockExample1 {  

  public static void main(String[] args) {  

    final String resource1 = "ratan jaiswal";  

    final String resource2 = "vimal jaiswal";  

    // t1 tries to lock resource1 then resource2  

    Thread t1 = new Thread() {  

      public void run() {  

[email protected]
Ph: 9014424466 Page 95
TechVeerendra’s
Software Solutions

          synchronized (resource1) {  

           System.out.println("Thread 1: locked resource 1");  

  

           try { Thread.sleep(100);} catch (Exception e) {}  

  

           synchronized (resource2) {  

            System.out.println("Thread 1: locked resource 2");  

           }  

         }  

      }  

    };  

  

    // t2 tries to lock resource2 then resource1  

    Thread t2 = new Thread() {  

      public void run() {  

        synchronized (resource2) {  

          System.out.println("Thread 2: locked resource 2");  

  

          try { Thread.sleep(100);} catch (Exception e) {}  

  

          synchronized (resource1) {  

            System.out.println("Thread 2: locked resource 1");  

          }  

[email protected]
Ph: 9014424466 Page 96
TechVeerendra’s
Software Solutions

        }  

      }  

    };  

  

      

    t1.start();  

    t2.start();  

  }  

}  

          

Output: Thread 1: locked resource 1

Thread 2: locked resource 2

Example:

class A

public synchronized void foo(B b)

System.out.println("Thread1 starts execution of foo()

method");

try

Thread.sleep(2000);

[email protected]
Ph: 9014424466 Page 97
TechVeerendra’s
Software Solutions

catch (InterruptedException e)

{}

System.out.println("Thread1 trying to call b.last()");

b.last();

public synchronized void last()

System.out.println("inside A, this is last()method");

class B

public synchronized void bar(A a)

System.out.println("Thread2 starts execution of bar() method");

try

Thread.sleep(2000);

catch (InterruptedException e)

{}

System.out.println("Thread2 trying to call a.last()");

a.last();

public synchronized void last()

[email protected]
Ph: 9014424466 Page 98
TechVeerendra’s
Software Solutions

System.out.println("inside B, this is last() method");

class DeadLock implements Runnable

A a=new A();

B b=new B();

DeadLock()

Thread t=new Thread(this);

t.start();

a.foo(b);//main thread

public void run()

b.bar(a);//child thread

public static void main(String[] args)

new DeadLock();//main thread

Output:
[email protected]
Ph: 9014424466 Page 99
TechVeerendra’s
Software Solutions

Thread1 starts execution of foo() method

Thread2 starts execution of bar() method

Thread2 trying to call a.last()

Thread1 trying to call b.last()

//here cursor always waiting.

Note : If we remove atleast one syncronized keywoed then we won't get


DeadLOck.Hence syncronized keyword in the only reason for DeadLock due to
this while using syncronized keyword we have to handling carefully.

Daemon Threads:

The Threads which are executing in the background are called daemon
Threads.

The main objective of daemon Threads is to provide support for non-daemon


Threads like main Thread.

Example:

Garbage collector

 Whenever the program runs with low memory the JVM will execute
Garbage Collector to provide free memory. So that the main Thread can
continue it's execution.
 We can check whether the Thread is daemon or not by using isDaemon()
method of Thread class.

public final boolean isDaemon();

 We can change daemon nature of a Thread by using setDaemon ()


method.

[email protected]
Ph: 9014424466 Page 100
TechVeerendra’s
Software Solutions

public final void setDaemon(boolean b);

 But we can change daemon nature before starting Thread only. That is
after starting the Thread if we are trying to change the daemon nature we
will get R.E

saying IllegalThreadStateException.

 Default Nature : Main Thread is always non daemon and we can't change
its daemon nature because it's already started at the beginning only.
 Main Thread is always non daemon and for the remaining Threads
daemon nature will be inheriting from parent to child that is if the parent
is daemon child is also daemon and if the parent is non daemon then
child is also non daemon.
 Whenever the last non daemon Thread terminates automatically all
daemon Threads will be terminated.

Example:

class MyThread extends Thread

class DaemonThreadDemo

public static void main(String[] args)

System.out.println(Thread.currentThread().isDaemon());

MyThread t=new MyThread();

System.out.println(t.isDaemon()); 1

[email protected]
Ph: 9014424466 Page 101
TechVeerendra’s
Software Solutions

t.start();

t.setDaemon(true);

System.out.println(t.isDaemon());

Output:

false

false

RE:IllegalThreadStateException

Example:

class MyThread extends Thread

public void run()

for(int i=0;i<10;i++)

System.out.println("lazy thread");

try

Thread.sleep(2000);

catch (InterruptedException e)

{}

[email protected]
Ph: 9014424466 Page 102
TechVeerendra’s
Software Solutions

class DaemonThreadDemo

public static void main(String[] args)

MyThread t=new MyThread();

t.setDaemon(true); //-->1

t.start();

System.out.println("end of main Thread");

Output:

End of main Thread

 If we comment line 1 then both main & child Threads are non-Daemon ,
and hence both threads will be executed untill there completion.
 If we are not comment line 1 then main thread is non-Daemon and child
thread is Daemon. Hence when ever main Thread terminates
automatically child thread will be terminated.

Lazy thread:

[email protected]
Ph: 9014424466 Page 103
TechVeerendra’s
Software Solutions

If we are commenting line 1 then both main and child Threads are non daemon
and hence both will be executed until they completion.

If we are not commenting line 1 then main Thread is non daemon and child
Thread is daemon and hence whenever main Thread terminates automatically
child Thread will be terminated.

Deadlock vs Starvation:

A long waiting of a Thread which never ends is called deadlock.

A long waiting of a Thread which ends at certain point is called starvation.

A low priority Thread has to wait until completing all high priority Threads.

This long waiting of Thread which ends at certain point is called starvation.

How to kill a Thread in the middle of the line?

We can call stop() method to stop a Thread in the middle then it will be entered
into dead state immediately.

public final void stop();

stop() method has been deprecated and hence not recommended to use.
suspend and resume methods:

A Thread can suspend another Thread by using suspend() method then that
Thread will be paused temporarily.

A Thread can resume a suspended Thread by using resume() method then


suspended Thread will continue its execution.

1. public final void suspend();

2. public final void resume();

[email protected]
Ph: 9014424466 Page 104
TechVeerendra’s
Software Solutions

Both methods are deprecated and not recommended to use.

RACE condition:

Executing multiple Threads simultaneously and causing data inconsistency


problems is nothing but Race condition we can resolve race condition by using
synchronized keyword.

Life cycle of a Thread:

[email protected]
Ph: 9014424466 Page 105
TechVeerendra’s
Software Solutions

Reentrant Monitor in Java:

According to Sun Microsystems, Java monitors are reentrant means java


thread can reuse the same monitor for different synchronized methods if
method is called from the method.

Advantage of Reentrant Monitor

It eliminates the possibility of single thread deadlocking

Ex:

class Reentrant {  

    public synchronized void m() {  

    n();  

    System.out.println("this is m() method");  

    }  

    public synchronized void n() {  

    System.out.println("this is n() method");  

    }  

}  

In this class, m and n are the synchronized methods. The m() method
internally calls the n() method.

Now let's call the m() method on a thread. In the class given below, we are
creating thread using annonymous class.

public class ReentrantExample{  

public static void main(String args[]){  

final ReentrantExample re=new ReentrantExample();  

[email protected]
Ph: 9014424466 Page 106
TechVeerendra’s
Software Solutions

  

Thread t1=new Thread(){  

public void run(){  

re.m();//calling method of Reentrant class  

}  

};  

t1.start();  

}}  

Output: this is n() method

this is m() method

[email protected]
Ph: 9014424466 Page 107
TechVeerendra’s
Software Solutions

Multi Threading Enhancements:


ThreadGroup:

 Based on the Functionality we can Group Threads into a Single Unit


which is Nothing but ThreadGroup i.e. ThreadGroup Represents a Set of
Threads.
 In Addition a ThreadGroup can Also contains Other SubThreadGroups.

ThreadGroup Class Present in java.lang Package and it is the Direct Child


Class of Object.

ThreadGroup provides a Convenient Way to Perform Common Operation for all


Threads belongs to a Particular Group.

Eg: Stop All Consumer Threads.

Suspend All Producer Threads.

Constructors:

1) ThreadGroup g = new ThreadGroup(String gname);

 Create a New ThreadGroup.

[email protected]
Ph: 9014424466 Page 108
TechVeerendra’s
Software Solutions

 The Parent of this New Group is the ThreadGroup of Currently Running


Thread.

2) ThreadGroup g = new ThreadGroup(ThreadGroup tg, String gname);

 Creates a New ThreadGroup.


 The Parent of this ThreadGroup is the specified ThreadGroup.

Note:

 In Java Every Thread belongs to Some Group.


 Every ThreadGroup is the Child Group of System Group either Directly
OR Indirectly. Hence SystemGroup Acts as Root for all ThreadGroup’s in
Java.
 System ThreadGroup Represents System Level Threads Like
ReferenceHandler, SignalDispatcher, Finalizer, AttachListener Etc.

[email protected]
Ph: 9014424466 Page 109
TechVeerendra’s
Software Solutions

Important Methods of ThreadGroup Class:

1) String getName();Returns Name of the ThreadGroup.

2) intgetMaxPriority();Returns the Maximum Priority of ThreadGroup.

3) void setMaxPriority();

[email protected]
Ph: 9014424466 Page 110
TechVeerendra’s
Software Solutions

 To Set Maximum Priority of ThreadGroup.


 The Default Maximum Priority is 10.
 Threads in the ThreadGroup that Already have Higher Priority, Not
effected but Newly Added Threads this MaxPriority is Applicable.

4) ThreadGroupgetParent(): Returns Parent Group of Current ThreadGroup.

5) void list(): It Prints Information about ThreadGroup to the Console.

6) intactiveCount(): Returns Number of Active Threads Present in the


ThreadGroup.

7) intactiveGroupCount(): It Returns Number of Active ThreadGroups Present


in the Current ThreadGroup.

8) int enumerate(Thread[] t): To Copy All Active Threads of this Group into
provided Thread Array. In this Case SubThreadGroup Threads also will be
Considered.

9) int enumerate(ThreadGroup[] g): To Copy All Active SubThreadGroups into

[email protected]
Ph: 9014424466 Page 111
TechVeerendra’s
Software Solutions

ThreadGroupArray

10) booleanisDaemon():

11) void setDaemon(boolean b):

12) void interrupt(): To Interrupt All Threads Present in the ThreadGroup.

13) void destroy(): To Destroy ThreadGroup and its SubThreadGroups.

Ex:

classMyThread extends Thread {

MyThread(ThreadGroup g, String name) {

super(g, name);

public void run() {

System.out.println("Child Thread");

try {

Thread.sleep(2000);

catch (InterruptedException e) {}

classThreadGroupDemo {

public static void main(String[] args) throws InterruptedException {

ThreadGrouppg = new ThreadGroup("Parent Group");

ThreadGroup cg = new ThreadGroup(pg, "Child Group");

MyThread t1 = new MyThread(pg, "Child Thread 1");

MyThread t2 = new MyThread(pg, "Child Thread 2");

[email protected]
Ph: 9014424466 Page 112
TechVeerendra’s
Software Solutions

t1.start();

t2.start();

System.out.println(pg.activeCount());

System.out.println(pg.activeGroupCount());

pg.list();

Thread.sleep(5000);

System.out.println(pg.activeCount());

pg.list();

Output:

java.lang.ThreadGroup[name=Parent Group,maxpri=10]

Thread[Child Thread 1,5,Parent Group]

Thread[Child Thread 2,5,Parent Group]

java.lang.ThreadGroup[name=Child Group,maxpri=10]

Child Thread

Child Thread

java.lang.ThreadGroup[name=Parent Group,maxpri=10]

java.lang.ThreadGroup[name=Child Group,maxpri=10]

[email protected]
Ph: 9014424466 Page 113
TechVeerendra’s
Software Solutions

ThreadLocal:

ThreadLocalProvides ThreadLocal Variables.

ThreadLocal Class Maintains Values for Thread Basis.

Each ThreadLocal Object Maintains a Separate Value Like userID,


transactionIDEtc for Each Thread that Accesses that Object.

Thread can Access its Local Value, can Manipulates its Value and Even can
Remove its Value.

In Every Part of the Code which is executed by the Thread we can Access its
Local Variables.

Eg:

Consider a Servlet which Calls Some Business Methods. we have a


Requirement to generate a Unique transactionID for Each and Every Request
and we have to Pass this transactionID to the Business Methods for Logging
Purpose.

[email protected]
Ph: 9014424466 Page 114
TechVeerendra’s
Software Solutions

For this Requirement we can Use ThreadLocal to Maintain a Separate


transactionID for Every Request and for Every Thread.

Note:

☀ ThreadLocal Class introduced in 1.2 Version.

☀ ThreadLocal can be associated with Thread Scope.

☀ All the Code which is executed by the Thread has Access to Corresponding
ThreadLocal Variables.

☀ A Thread can Access its Own Local Variables and can’t Access Other
ThreadsLocal Variables.

☀ Once Thread Entered into Dead State All Local Variables are by Default
Eligible for Garbage Collection.

Constructor:ThreadLocaltl = new ThreadLocal(); Creates a ThreadLocal


Variable.

Methods:

1) Object get(); Returns the Value of ThreadLocal Variable associated with


Current Thread.

2) Object initialValue();

 Returns the initialValue of ThreadLocal Variable of Current Thread.


 The Default Implementation of initialValue() Returns null.
 To Customize Our initialValue we have to Override initialValue().

3) void set(Object newValue);To Set a New Value.

4) void remove();

[email protected]
Ph: 9014424466 Page 115
TechVeerendra’s
Software Solutions

 To Remove the Current Threads Local Variable Value.


 After Remove if we are trying to Access it will be reinitialized Once Again
by invoking its initialValue().
 This Method Newly Added in 1.5 Version.

Ex:

[email protected]
Ph: 9014424466 Page 116
TechVeerendra’s
Software Solutions

ThreadLocalVs Inheritance:

 Parent Threads ThreadLocal Variables are by Default Not Available to the


Child Threads.
 If we want to Make Parent Threads Local Variables Available to Child
Threads we should go for InheritableThreadLocal Class.
 It is the Child Class of ThreadLocal Class.
 By Default Child Thread Values are Same as Parent Thread Values but
we can Provide Customized Values for Child Threads by Overriding
childValue().

Constructor:InheritableThreadLocalitl = new InheritableThreadLocal();

InheritableThreadLocal is the Child Class of ThreadLocal and Hence All


Methods Present in ThreadLocal by Default Available to the
InheritableThreadLocal.

Method: public Object childValue(Object pvalue);

Ex:

classParentThread extends Thread {

public static InheritableThreadLocalitl = new InheritableThreadLocal() {

public Object childValue(Object p) {

return "cc";

};

public void run() {

itl.set("pp");

System.out.println("Parent Thread --"+itl.get());

ChildThreadct = new ChildThread();

[email protected]
Ph: 9014424466 Page 117
TechVeerendra’s
Software Solutions

ct.start();

classChildThread extends Thread {

public void run() {

System.out.println("Child Thread --"+ParentThread.itl.get());

classThreadLocalDemo {

public static void main(String[] args) {

ParentThreadpt = new ParentThread();

pt.start();

Java.util.concurrent.locks package:

Problems with Traditional synchronized Key Word

If a Thread Releases the Lock then which waiting Thread will get that Lock we
are Not having any Control on this.

We can’t Specify Maximum waiting Time for a Thread to get Lock so that it will
Wait until getting Lock, which May Effect Performance of the System and
Causes Dead Lock.

We are Not having any Flexibility to Try for Lock without waiting.

There is No API to List All Waiting Threads for a Lock.

[email protected]
Ph: 9014424466 Page 118
TechVeerendra’s
Software Solutions

The synchronized Key Word Compulsory we have to Define within a Method


and it is Not Possible to Declare Over Multiple Methods.

To Overcome Above Problems SUN People introduced java.util.concurrent.locks


Package in 1.5 Version.

It Also Provides Several Enhancements to the Programmer to Provide More


Control on Concurrency.

Lock(I):

A Lock Object is Similar to Implicit Lock acquired by a Thread to Execute


synchronized Method OR synchronized Block

Lock Implementations Provide More Extensive Operations than Traditional


Implicit Locks.

Important Methods of Lock Interface

1) void lock();

 It Locks the Lock Object.


 If Lock Object is Already Locked by Other Thread then it will wait until it
is Unlocked.

2) booleantryLock();

 To Acquire the Lock if it is Available.


 If the Lock is Available then Thread Acquires the Lock and Returns true.
 If the Lock Unavailable then this Method Returns false and Continue its
Execution.
 In this Case Thread is Never Blocked.

[email protected]
Ph: 9014424466 Page 119
TechVeerendra’s
Software Solutions

3) boolentryLock(long time, TimeUnit unit);

To Acquire the Lock if it is Available.

If the Lock is Unavailable then Thread can Wait until specified Amount of Time.

Still if the Lock is Unavailable then Thread can Continue its Execution.

Eg: if (l.tryLock(1000, TimeUnit.SECONDS)) {}

4) void lockInterruptedly();

Acquired the Lock Unless the Current Thread is Interrupted. Acquires the Lock
if it is Available and Returns Immediately.

If it is Unavailable then the Thread will wait while waiting if it is Interrupted


then it won’t get the Lock.

[email protected]
Ph: 9014424466 Page 120
TechVeerendra’s
Software Solutions

5) void unlock(); To Release the Lock.

ReentrantLock

It implements Lock Interface and it is the Direct Child Class of an Object.

Reentrant Means a Thread can acquires Same Lock Multiple Times without any
Issue.

Internally ReentrantLock Increments Threads Personal Count whenever we


Call lock() and Decrements Counter whenever we Call unlock() and Lock will be

Released whenever Count Reaches ‘0’.

Constructors:

1) ReentrantLockrl = new ReentrantLock();

Creates an Instance of ReentrantLock.

2) ReentrantLockrl = new ReentrantLock(boolean fairness);

Creates an Instance of ReentrantLock with the Given Fairness Policy.

If Fairness is true then Longest Waiting Thread can acquired Lock Once it is
Avaiable i.e. if follows First - In First – Out.

If Fairness is false then we can’t give any Guarantee which Thread will get the
Lock Once it is Available.

Note: If we are Not specifying any Fairness Property then by Default it is Not
Fair.

[email protected]
Ph: 9014424466 Page 121
TechVeerendra’s
Software Solutions

Important Methods of ReentrantLock

1) void lock();

2) booleantryLock();

3) booleantryLock(long l, TimeUnit t);

4) void lockInterruptedly();

5) void unlock();

To Realease the Lock.

If the Current Thread is Not Owner of the Lock then we will get Runtime
Exception Saying IllegalMonitorStateException.

6) intgetHoldCount(); Returns Number of Holds on this Lock by Current


Thread.

7) booleanisHeldByCurrentThread(); Returns true if and Only if Lock is Hold by


8) intgetQueueLength(); Returns the Number of Threads waiting for the Lock.

9) Collection getQueuedThreads(); Returns a Collection containing Thread


Objects which are waiting to get the Lock.

[email protected]
Ph: 9014424466 Page 122
TechVeerendra’s
Software Solutions

10) booleanhasQueuedThreads(); Returns true if any Thread waiting to get the


Lock.

11) booleanisLocked(); Returns true if the Lock acquired by any Thread.

12) booleanisFair();Returns true if the Lock’s Fairness Set to true.

13) Thread getOwner();Returns the Thread which acquires the Lock.

Ex:

importjava.util.concurrent.locks.ReentrantLock;

class Test {

public static void main(String[] args) {

ReentrantLock l = new ReentrantLock();

l.lock();

l.lock();

System.out.println(l.isLocked()); //true

System.out.println(l.isHeldByCurrentThread()); //true

System.out.println(l.getQueueLength()); //0

l.unlock();

System.out.println(l.getHoldCount()); //1

System.out.println(l.isLocked()); //true

l.unlock();

System.out.println(l.isLocked()); //false

System.out.println(l.isFair()); //false

[email protected]
Ph: 9014424466 Page 123
TechVeerendra’s
Software Solutions

Ex:

importjava.util.concurrent.locks.ReentrantLock;

class Display {

ReentrantLock l = new ReentrantLock(true);

public void wish(String name) {

l.lock(); 1

for(int i=0; i<5; i++) {

System.out.println("Good Morning");

try {

Thread.sleep(2000);

catch(InterruptedException e) {}

System.out.println(name);

l.unlock(); 2

classMyThread extends Thread {

Display d;

String name;

MyThread(Display d, String name) {

this.d = d;

this.name = name;

[email protected]
Ph: 9014424466 Page 124
TechVeerendra’s
Software Solutions

public void run() {

d.wish(name);

classReentrantLockDemo {

public static void main(String[] args) {

Display d = new Display();

MyThread t1 = new MyThread(d, "Dhoni");

MyThread t2 = new MyThread(d, "Yuva Raj");

MyThread t3 = new MyThread(d, "ViratKohli");

t1.start();

t2.start();

t3.start();

Output:

Good Morning

Dhoni

Good Morning

Dhoni

Good Morning

Dhoni

[email protected]
Ph: 9014424466 Page 125
TechVeerendra’s
Software Solutions

Good Morning

Dhoni

Good Morning

Dhoni

Good Morning

Yuva Raj

Good Morning

Yuva Raj

Good Morning

Yuva Raj

Good Morning

Yuva Raj

Good Morning

Yuva Raj

Good Morning

ViratKohli

Good Morning

ViratKohli

Good Morning

ViratKohli

Good Morning

ViratKohli

Good Morning

[email protected]
Ph: 9014424466 Page 126
TechVeerendra’s
Software Solutions

ViratKohli

If we Comment Both Lines 1 and 2 then All Threads will be executed


Simultaneously and Hence we will get Irregular Output.

If we are Not Commenting then the Threads will be executed One by One and
Hence we will get Regular Output

Demo Program To Demonstrate tryLock();

importjava.util.concurrent.locks.ReentrantLock;

classMyThread extends Thread {

staticReentrantLock l = new ReentrantLock();

MyThread(String name) {

super(name);

public void run() {

if(l.tryLock()) {

SOP(Thread.currentThread().getName()+" Got Lock and Performing Safe


Operations");

try {

Thread.sleep(2000);

catch(InterruptedException e) {}

l.unlock();

else {

System.out.println(Thread.currentThread().getName()+" Unable To Get Lock

[email protected]
Ph: 9014424466 Page 127
TechVeerendra’s
Software Solutions

and Hence Performing Alternative Operations");

classReentrantLockDemo {

public static void main(String args[]) {

MyThread t1 = new MyThread("First Thread");

MyThread t2 = new MyThread("Second Thread");

t1.start();

t2.start();

Output:

First Thread Got Lock and Performing Safe Operations

Second Thread Unable To Get Lock and Hence Performing Alternative


Operations

Ex:

importjava.util.concurrent.TimeUnit;

importjava.util.concurrent.locks.ReentrantLock;

classMyThread extends Thread {

staticReentrantLock l = new ReentrantLock();

MyThread(String name) {

super(name);

}
[email protected]
Ph: 9014424466 Page 128
TechVeerendra’s
Software Solutions

public void run() {

do {

try {

if(l.tryLock(1000, TimeUnit.MILLISECONDS)) {

SOP(Thread.currentThread().getName()+"------- Got Lock");

Thread.sleep(5000);

l.unlock();

SOP(Thread.currentThread().getName()+"------- Releases Lock");

break;

else {

SOP(Thread.currentThread().getName()+"------- Unable To Get Lock And Will


Try Again");

catch(InterruptedException e) {}

while(true);

classReentrantLockDemo {

public static void main(String args[]) {

MyThread t1 = new MyThread("First Thread");

MyThread t2 = new MyThread("Second Thread");

t1.start();

t2.start();

[email protected]
Ph: 9014424466 Page 129
TechVeerendra’s
Software Solutions

Output:

First Thread------- Got Lock

Second Thread------- Unable To Get Lock And Will Try Again

Second Thread------- Unable To Get Lock And Will Try Again

Second Thread------- Unable To Get Lock And Will Try Again

Second Thread------- Unable To Get Lock And Will Try Again

Second Thread------- Got Lock

First Thread------- Releases Lock

Second Thread------- Releases Lock

Thread Pools:

Creating a New Thread for Every Job May Create Performance and Memory
Problems.

To Overcome this we should go for Thread Pool Concept.

Thread Pool is a Pool of Already Created Threads Ready to do Our Job.

Java 1.5 Version Introduces Thread Pool Framework to Implement Thread


Pools.

Thread Pool Framework is Also Known as Executor Framework.

We can Create a Thread Pool as follows ExecutorService service =


Executors.newFixedThreadPool(3);//Our Choice

We can Submit a Runnable Job by using submit().

service.submit(job);

[email protected]
Ph: 9014424466 Page 130
TechVeerendra’s
Software Solutions

We can ShutdownExecutiorService by using shutdown().

service.shutdown();

importjava.util.concurrent.ExecutorService;

importjava.util.concurrent.Executors;

classPrintJob implements Runnable {

String name;

PrintJob(String name) {

this.name = name;

public void run() {

SOP(name+"....Job Started By Thread:" +Thread.currentThread().getName());

try {

Thread.sleep(10000);

catch (InterruptedException e) {}

SOP(name+"....Job Completed By Thread:" +Thread.currentThread().getName());

class ExecutorDemo {

public static void main(String[] args) {

PrintJob[] jobs = {

newPrintJob("Durga"),

[email protected]
Ph: 9014424466 Page 131
TechVeerendra’s
Software Solutions

newPrintJob("Ravi"),

newPrintJob("Nagendra"),

newPrintJob("Pavan"),

newPrintJob("Bhaskar"),

newPrintJob("Varma")

};

ExecutorService service = Executors.newFixedThreadPool(3);

for (PrintJob job : jobs) {

service.submit(job);

service.shutdown();

Output:

Durga....Job Started By Thread:pool-1-thread-1

Ravi....Job Started By Thread:pool-1-thread-2

Nagendra....Job Started By Thread:pool-1-thread-3

Ravi....Job Completed By Thread:pool-1-thread-2

Pavan....Job Started By Thread:pool-1-thread-2

Durga....Job Completed By Thread:pool-1-thread-1

Bhaskar....Job Started By Thread:pool-1-thread-1

Nagendra....Job Completed By Thread:pool-1-thread-3

Varma....Job Started By Thread:pool-1-thread-3

[email protected]
Ph: 9014424466 Page 132
TechVeerendra’s
Software Solutions

Pavan....Job Completed By Thread:pool-1-thread-2

Bhaskar....Job Completed By Thread:pool-1-thread-1

Varma....Job Completed By Thread:pool-1-thread-3

On the Above Program 3 Threads are Responsible to Execute 6 Jobs. So that a


Single Thread can be reused for Multiple Jobs.

Note: Usually we can Use ThreadPool Concept to Implement Servers (Web


Servers And Application Servers).

Callable and Future:

 In the Case of Runnable Job Thread won’t Return anything.


 If a Thread is required to Return Some Result after Execution then we
should go for Callable.
 Callable Interface contains Only One Method public Object call() throws
Exception.
 If we Submit a Callable Object to Executor then the Framework Returns
an Object of Type java.util.concurrent.Future
 The Future Object can be Used to Retrieve the Result from Callable Job.

[email protected]
Ph: 9014424466 Page 133

You might also like