0% found this document useful (0 votes)
28 views159 pages

THREAD

Typically, we can define threads as a subprocess with lightweight with the smallest unit of processes and also has separate paths of execution. The main advantage of multiple threads is efficiency (allowing multiple things at the same time. For example, in MS Word. one thread automatically formats the document while another thread is taking user input. Another advantage is quick response, if we use multiple threads in a process and if a thread gets stuck due to lack of resources or an exception,

Uploaded by

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

THREAD

Typically, we can define threads as a subprocess with lightweight with the smallest unit of processes and also has separate paths of execution. The main advantage of multiple threads is efficiency (allowing multiple things at the same time. For example, in MS Word. one thread automatically formats the document while another thread is taking user input. Another advantage is quick response, if we use multiple threads in a process and if a thread gets stuck due to lack of resources or an exception,

Uploaded by

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

JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

THREAD IN JAVA
 WHAT ARE JAVA THREADS?
A thread is defined as a separate stream of implementation that takes place simultaneously with and
independently of everything else that might be happening. It does not have an event loop. A thread runs
autonomously of anything else happening in the computer. With threads the other tasks that don't get stuck
in the loop can continue processing without waiting for the stuck task to terminate. A thread is a coding that
doesn't affect the architecture of an application. Threading is equally separate the computer's power among
different tasks. Threading concept is very important in Java Programing language. A thread is a sequential path
of code execution within a program. And each thread has its own local variables, program counter and
lifetime.
So, a thread is an independent path of execution within a program. Many threads can run concurrently within
a program. Every thread in Java is created and controlled by the java.lang.Thread class.
So, thread is a:
 Facility to allow multiple activities within a single process.
 Referred as lightweight process.
 A thread is a series of executed statements.
 Each thread has its own program counter, stack and local variables.
 A thread is a nested sequence of method calls.
 Its shares memory, files and per-process state.
 WHAT IS THE NEED OF A THREAD OR WHY USE THREADS?
 To perform asynchronous or background processing.
 Increases the responsiveness of GUI applications.
 TAKE ADVANTAGE OF MULTIPROCESSOR SYSTEMS
 Simplify program logic when there are multiple independent entities.
 WHAT HAPPENS WHEN A THREAD IS INVOKED?
When a thread is invoked, there will be two paths of execution. One path will execute the thread and the
other path will follow the statement after the thread invocation. There will be a separate stack and memory
space for each thread.
 RISK FACTOR
 Proper co-ordination is required between threads accessing common variables [use of synchronized
and volatile] for consistence view of data.
 Overuse of java threads can be hazardous to program’s performance and its maintainability.

 JAVA THREADS FACILITY AND API IS DECEPTIVELY SIMPLE:


Every java program creates at least one thread [ main() thread ]. Additional threads are created
through the Thread constructor or by instantiating classes that extend the Thread class.

1
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 THREAD CREATION IN JAVA


 Thread implementation in java can be achieved in two ways:
1. Extending the java.lang.Thread class
2. Implementing the java.lang.Runnable Interface
NOTE: The Thread and Runnable are available in the java.lang.* package.

1) BY EXTENDING THREAD CLASS- by extending java.lang.Thread class


 The class should extend Java Thread class.
 The class should override the run() method.
• The functionality that is expected by the Thread to be executed is written in the run() method.
 void start(): Creates a new thread and makes it runnable.
 void run(): The new thread begins its life inside this method.
 This approach provides more flexibility in handling multiple threads created using available methods
in Thread class.
• STEP 1
Need to override run( ) method available in Thread class. This method provides entry point for the thread and
you will put you complete business logic inside this method.
Following is simple syntax of run() method: public void run( )
• STEP 2
Once Thread object is created, you can start it by calling start( ) method, which executes a call to run( )
method. Following is simple syntax of start() method: void start( );
EXAMPLE:
 HERE IS THE PRECEDING PROGRAM REWRITTEN TO EXTEND THREAD:
class ThreadDemo extends Thread
{
private Thread t;
private String threadName;
ThreadDemo( String name)
{
threadName = name;
System.out.println("Creating " + threadName );
}
public void run()
{
System.out.println("Running " + threadName );
try
{
for(int i = 4; i > 0; i--)
{
System.out.println("Thread: " + threadName + ", " + i);
// Let the thread sleep for a while.
Thread.sleep(50);
}
} catch (InterruptedException e)
{
System.out.println("Thread " + threadName + " interrupted.");
}
System.out.println("Thread " + threadName + " exiting."); }

2
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

public void start ()


{ THIS WOULD PRODUCE THE FOLLOWING RESULT:
System.out.println("Starting " + threadName ); Creating Thread-1
if (t == null) Starting Thread-1
{ Creating Thread-2
t = new Thread (this, threadName); Starting Thread-2
t.start (); Running Thread-1
} Thread: Thread-1, 4
} Running Thread-2
} Thread: Thread-2, 4
public class TestThread Thread: Thread-1, 3
{ Thread: Thread-2, 3
public static void main(String args[]) Thread: Thread-1, 2
{ Thread: Thread-2, 2
ThreadDemo T1 = new ThreadDemo( "Thread-1"); Thread: Thread-1, 1
T1.start(); Thread: Thread-2, 1
ThreadDemo T2 = new ThreadDemo( "Thread-2"); Thread Thread-1 exiting.
T2.start(); Thread Thread-2 exiting.
}
}
 EXAMPLE:
public class MyThread extends Thread
{
public void run()
{
System.out.println("thread is running...");
}
public static void main(String[] args)
{
MyThread obj = new MyThread();
obj.start();
}
 ANOTHER EXAMPLE:-
class MyThread extends Thread
{
public void run()
{
//Keep the task to be performed here
}
}
public class MainClass
{
public static void main(String[] args)
{
MyThread thread = new MyThread();
thread.start();
}
}

3
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 This is another way to create a thread by a new class that extends Thread class and create an
instance of that class. The extending class must override run() method which is the entry point of
new thread.
class MyThread extends Thread
{
public void run()
{
System.out.println("Concurrent thread started running..");
}
}
classMyThreadDemo
{
public static void main( String args[] )
{
MyThread mt = new MyThread();
mt.start();
}
}
Output : concurrent thread started running..
NOTE:-
In this case also, as we must override the run() and then use the start() method to start and run the thread.
Also, when you create MyThread class object, Thread class constructor will also be invoked, as it is the super
class, hence MyThread class object acts as Thread class object.
 By extending Thread class:
class Multi extends Thread
{
public void run()
{
System.out.println("thread is running...");
}
public static void main(String args[])
{
Multi t1=new Multi();
t1.start();
}
}
Output: thread is running...
Note : But the problem with this approach is that class can not extend any more class,run method can be
overloaded in class. but only run() method(without argument) will be consider by JVM. Any other overridden
method will needs to be called explicitly.

 2) BY IMPLEMENTING RUNNABLE INTERFACE- by


implementing java.lang.Runnable interface.
• The thread moves from New state to the Runnable state.When the thread gets a chance to execute, its
target run() method will run.
• The class should implement the Runnable interface.
• The class should implement the run() method in the Runnable interface.
• The functionality that is expected by the Thread to be executed is put in the run() method.
4
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 Class is intended to be executed as a thread then you can achieve this by


implementing Runnable interface. You will need to follow three basic steps:
• STEP 1:
As a first step you need to implement a run() method provided by Runnable interface. This method provides
entry point for the thread and you will put you complete business logic inside this method.
Following is simple syntax of run() method: public void run( )
• STEP 2:
At second step you will instantiate a Thread object using the following constructor:
Thread(Runnable threadObj, String threadName);
Where, threadObj is an instance of a class that implements the Runnableinterface and threadName is the
name given to the new thread.
• STEP 3
Once Thread object is created, you can start it by calling start( ) method, which executes a call to run( )
method.
Following is simple syntax of start() method: void start( );
• Example:Here is an example that creates a new thread and starts it running:
class RunnableDemo implements Runnable
{
private Thread t;
private String threadName;
RunnableDemo( String name)
{
threadName = name;
System.out.println("Creating " + threadName );
}
public void run()
{ This would produce the following result:
System.out.println("Running " + threadName ); Creating Thread-1
Try Starting Thread-1
{ Creating Thread-2
for(int i = 4; i > 0; i--) Starting Thread-2
{ Running Thread-1
System.out.println("Thread: " + threadName + ", " + i); Thread: Thread-1, 4
// Let the thread sleep for a while. Running Thread-2
Thread.sleep(50); Thread: Thread-2, 4
} Thread: Thread-1, 3
} Thread: Thread-2, 3
catch (InterruptedException e) Thread: Thread-1, 2
{ Thread: Thread-2, 2
System.out.println("Thread " + threadName + " Thread: Thread-1, 1
interrupted."); Thread: Thread-2, 1
} Thread Thread-1 exiting.
System.out.println("Thread " + threadName + " exiting."); Thread Thread-2 exiting.
}

5
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

public void start ()


{
System.out.println("Starting " + threadName );
if (t == null)
{
t = new Thread (this, threadName);
t.start ();
}
}
}
public class TestThread
{
public static void main(String args[])
{
RunnableDemo R1 = new RunnableDemo( "Thread-1");
R1.start();
RunnableDemo R2 = new RunnableDemo( "Thread-2");
R2.start();
}
}
 ANOTHER EXAMPLE:-
class Multi3 implements Runnable
{
public void run()
{
System.out.println("thread is running...");
}
public static void main(String args[])
{
Multi3 m1=new Multi3();
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 your class that implements
Runnable so that your class run() method may execute.

6
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 Example The following ThreadClassDemo program demonstrates some of these


methods of the Thread class and implement Runnable interface in combine. Consider
a class DisplayMessage which implements Runnable:
• // Create a thread to implement Runnable
public class DisplayMessage implements Runnable
{
private String message;
public DisplayMessage(String message)
{
this.message = message;
}
public void run()
{
while(true)
{
System.out.println(message);
}
}
}
• //Following is another class which extends Thread class:
public class GuessANumber extends Thread
{
private int number;
public GuessANumber(int number)
{
this.number = number;
}
public void run()
{
int counter = 0;
int guess = 0;
do
{
guess = (int) (Math.random() * 100 + 1);
System.out.println(this.getName()
+ " guesses " + guess);
counter++;
}
while(guess != number);
System.out.println("Correct! " + this.getName() + " in " + counter + " guesses.");
}
}

7
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

• // Following is the main program which makes use of above defined classes:
public class ThreadClassDemo
{
public static void main(String [] args)
{ OUTPUT:-
Runnable hello = new DisplayMessage("Hello"); Starting hello thread...
Thread thread1 = new Thread(hello); Starting goodbye thread...
thread1.setDaemon(true); Hello
thread1.setName("hello"); Hello
System.out.println("Starting hello thread..."); Hello
thread1.start(); Hello
Runnable bye = new DisplayMessage("Goodbye"); Hello
Thread thread2 = new Thread(bye); Hello
thread2.setPriority(Thread.MIN_PRIORITY); Goodbye
thread2.setDaemon(true); Goodbye
System.out.println("Starting goodbye thread..."); Goodbye
thread2.start(); Goodbye
System.out.println("Starting thread3..."); Goodbye
Thread thread3 = new GuessANumber(27); .......
thread3.start();
try
{
thread3.join(); NOTE:-
}catch(InterruptedException e) This would produce the following result.
{ You can try this example again and again
System.out.println("Thread interrupted."); and you would get different result every
} time.
System.out.println("Starting thread4...");
Thread thread4 = new GuessANumber(75);
thread4.start();
System.out.println("main() is ending...");
}
}

8
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 SUBCLASS THREAD.
The Thread class itself implements Runnable, though its run method does nothing. An application can
subclass Thread, providing its own implementation of run, as in the HelloThread example:
• EXAMPLE:-
public class HelloThread extends Thread
{
public void run()
{
System.out.println("Hello from a thread!");
}
public static void main(String args[])
{
(new HelloThread()).start();
}
}
• EXAMPLE:
public class MyThread implements Runnable
{
public void run()
{
System.out.println("thread is running..");
}
public static void main(String[] args)
{
Thread t = new Thread(new MyThread());
t.start();
}
• ANOTHER EXAMPLE:-
class MyRunnable implements Runnable
{
public void run()
{
//Keep the task to be performed here
}
}
public class MainClass
{
public static void main(String[] args)
{
MyRunnable runnable = new MyRunnable();
Thread t = new Thread(runnable);
t.start();
}
}
NOTE: -The easiest way to create a thread is to create a class that implements the runnable interface. After
implementing runnable interface , the class needs to implement the run() method, which is of form,

9
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 public void run()


run() method introduces a concurrent thread into your program. This thread will end when run() returns, must
specify the code for the thread inside run() method;run() method can call other methods, can use other
classes and declare variables just like any other normal method.
• EXAMPLE:-
class MyThread implements Runnable
{
public void run()
{
System.out.println("concurrent thread started running..");
}
}
class MyThreadDemo
{
public static void main( String args[] )
{
MyThread mt = new MyThread();
Thread t = new Thread(mt);
t.start();
}
}
Output : concurrent thread started running..
NOTE: -To call the run() method, start() method is used. On calling start(), a new stack is provided to the
thread and run() method is called to introduce the new thread into the program.

10
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 EXTENDS THREAD CLASS VS IMPLEMENTS RUNNABLE INTERFACE?


Extending the Thread class will make your class unable to extend other classes, because of the single
inheritance feature in JAVA. However, this will give you a simpler code structure. If you implement Runnable,
you can gain better object-oriented design and consistency and also avoid the single inheritance problems.
If you just want to achieve basic functionality of a thread you can simply implement Runnable interface and
override run() method. But if you want to do something serious with thread object as it has other methods
like suspend(), resume(), ..etc which are not available in Runnable interface then you may prefer to extend
the Thread class.
 DIFFERENCES BETWEEN EXTENDS THREAD AND IMPLEMENTS RUNNABLE IN JAVA :
1) MULTIPLE INHERITANCE LIMITATION
Java doesn’t support multiple inheritance. A class in java can extend only one class. If you extend Thread class,
then your class will not be able to extend any other class. This will limit your class to thread behavior. If you
implement Runnable interface, then you will have an option for your class to extend any other class and
inherit behaviors from other class also.
2) OVERHEAD OF ADDITIONAL METHODS
If you extend Thread class, all methods of Thread class will be inheriting to your class which you may not need.
This will cause additional overhead. You can remove this overhead by implementing Runnable interface.
3) LOGICAL SEPARATION OF TASK FROM THE RUNNER
If you implement Runnable interface, it will separate actual task from the runner. Runnable interface
represents only the task and you can pass this task to any type of runner, either a thread or any executors.
4) BEST OBJECT ORIENTED DESIGN PRACTICE
In object oriented programming, extending a class means modifying or improving the existing class. If you are
not improving the class, then it is not a good practice to extend it. So, implementing Runnable will be the best
object oriented design practice.
5) LOOSELY COUPLED VS TIGHTLY COUPLED
“Implements Runnable” makes your code loosely coupled. Because it separates the task from the runner.
“Extends Thread” will make your code tightly coupled. Because, single class will act as both task container as
well as runner.
6) REUSABILITY
Implementing Runnable improves the reusability of your code. Because, Runnable contains only the task and
you can use it wherever and whenever you want.
7) SPECIALIZATION VS GENERALIZATION
“Extends Thread” gives more specialized code. Because, it defines the thread specific task. Where as
“Implements Runnable” gives more generalized version of the task applicable to many threads.
8) MAINTENANCE
“Implements Runnable” will make your code easily maintainable as it separates the task from the runner. If
you want to modify the task at any time, you can do so easily without disturbing the runner.

11
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 EXTENDS THREAD VS IMPLEMENTS RUNNABLE IN JAVA :

IMPLEMENTS RUNNABLE EXTENDS THREAD

You can extend any other class. You can’t extend any other class.

Overhead of additional methods from


No overhead of additional methods . Thread class.

Separates the task from the runner. Doesn’t separate the task from the runner.

Best object oriented Not a good object oriented programming


programming practice. practice.

Loosely coupled. Tightly coupled.

Doesn’t improve the reusability of the


Improves the reusability of the code. code.

More generalized task. Thread specific task.

Maintenance of the code will be time


Maintenance of the code will be easy. consuming.

12
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 INSTANTIATING THREAD :
Every thread of execution begins as an instance of class Thread. In any case Thread objects needs to be
created before creating Thread of Execution.
Creating Thread object is different for both the cases. In case of Extending Thread class you can directly
initiate class with new keyword as it has extended Thread class itself.
MyThread t = new MyThread()
In case of implementing Runnable interface. First created runnable class needs to be instantiated.
MyRunnable r = new MyRunnable();
 Now pass this runnable object to Thread.
Thread t = new Thread(r);
If create a thread using the no-arg constructor, the thread will call its own run(). This happened in first
case(Extending Thread class) But in case of Runnable Thread class needs to know that run method from class
implementing runnable interface needs to be invoked instead of run() from Thread class. So we need to pass
the class as argument to Thread.
 Single runnable instance can be passed to multiple Thread object.
public class TestThreads
{
public static void main (String [] args)
{
MyRunnable r = new MyRunnable();
Thread foo = new Thread(r);
Thread bar = new Thread(r);
Thread bat = new Thread(r);
}
}
NOTE : Giving the same target to multiple threads means that several threads of execution will be running the
very same job .The Thread class itself implements Runnable. (After all, it has a run() method that we were
overriding.) This means that you could pass a Thread to another Thread’s constructor.

 OVERLOADED CONSTRUCTOR IN THREAD CLASS:


• Thread()
• Thread(Runnable target)
• Thread(Runnable target, String name)
• Thread(String name)
NOTE:-
Till now we have created Thread object and it knows what to do in form of run() method. But till now it is still
an object. It does not have its own call stack. In other words Thread of execution has not been started. A
Thread object will have its own stack only when start() method will be called on Thread.

 Thread has 2 states.


 New state (Thread object created but Start method not invoked)
 runnable(alive) state (start method is invoked )
NOTE : Calling run() method from java code directly mean that you are invoking a method and stack will not
be created.When a Thread is in runnable state means Thread is created but it’s run method is not yet
executed and thread is waiting for his turn. Once Thread got selected thread’s run method will execute and
that state will called running state.
13
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 THREAD CLASS ALSO DEFINES MANY METHODS FOR MANAGING THREADS.

METHOD DESCRIPTION
setName() to give thread a name

getName() return thread's name

getPriority() return thread's priority

isAlive() checks if thread is still running or not

join() Wait for a thread to end

run() Entry point for a thread

sleep() suspend thread for a specified time

start() start a thread by calling run() method

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


• SYNTAX:-
 public String getName()
 public void setName(String name)
 public long getId()
class TestJoinMethod3 extends Thread
{ Output:
public void run() Name of t1:Thread-0
{ Name of t2:Thread-1
System.out.println("running..."); id of t1:8
} running...
public static void main(String args[]) After changling name of t1:Sonoo
{ Jaiswal
TestJoinMethod3 t1=new TestJoinMethod3(); running...
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());
}
}

14
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 The currentThread() method:


The currentThread() method returns a reference to the currently executing thread object.
 Syntax: public static Thread currentThread()
 Example of currentThread() method
class TestJoinMethod4 extends Thread Output:
{ Thread-0
public void run() Thread-1
{
System.out.println(Thread.currentThread().getName());
}
}
public static void main(String args[])
{
TestJoinMethod4 t1=new TestJoinMethod4();
TestJoinMethod4 t2=new TestJoinMethod4();
t1.start();
t2.start();
}
}
 Naming a thread:
The Thread class provides methods to change and get the name of a thread.
 public String getName(): is used to return the name of a thread.
 public void setName(String name): is used to change the name of a thread.
• Example of naming a thread:
class TestMultiNaming1 extends Thread
Output:
{
Name of t1:Thread-0
public void run()
Name of t2:Thread-1
{
id of t1:8
System.out.println("running...");
running...
}
After changeling name of t1:Sonoo Jaiswal
public static void main(String args[])
running...
{
TestMultiNaming1 t1=new TestMultiNaming1();
TestMultiNaming1 t2=new TestMultiNaming1();
System.out.println("Name of t1:"+t1.getName());
System.out.println("Name of t2:"+t2.getName());
t1.start();
t2.start();
t1.setName("Sonoo Jaiswal");
System.out.println("After changing name of t1:"+t1.getName());
}
}

15
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 SOME IMPORTANT POINTS TO REMEMBER


 When we extend Thread class, we cannot override setName() and getName() functions, because they
are declared final in Thread class.
 While using sleep(), always handle the exception it throws.
 static void sleep(long milliseconds) throws InterruptedException

 What if we call run() method directly without using start() method ?


In above program if we directly call run() method, without using start() method,
public static void main( String args[] )
{
MyThread mt = new MyThread();
mt.run();
}
NOTE:-Doing so, the thread won't be allocated a new call stack, and it will start running in the current call
stack, that is the call stack of the main thread. Hence Multithreading won't be there.

 Can we Start a thread twice ?


No, a thread cannot be started twice. If you try to do so, IllegalThreadStateException will be thrown.
public static void main( String args[] )
{
MyThread mt = new MyThread();
mt.start();
mt.start(); //Exception thrown
}
When a thread is in running state, and you try to start it again, or any method try to invoke that thread again
using start() method, exception is thrown.

16
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 JOINING THREADS
• Sometimes one thread needs to know when another thread is ending. In java, isAlive() and join() are
two different methods to check whether a thread has finished its execution.
• The isAlive() methods return true if the thread upon which it is called is still running otherwise it
return false.
 final boolean isAlive()
But, join() method is used more commonly than isAlive(). This method waits until the thread on which it is
called terminates.
 final void join() throws InterruptedException
Using join() method, we tell our thread to wait until the specified thread completes its execution. There are
overloaded versions of join() method, which allows us to specify time for which you want to wait for the
specified thread to terminate.
 final void join(long milliseconds) throws InterruptedException
 Example of isAlive method
public class MyThread extends Thread
{
public void run()
{
System.out.println("r1 ");
try
{
Thread.sleep(500); Output
} catch(InterruptedException ie) { } r1
System.out.println("r2 "); true
} true
public static void main(String[] args) r1
{ r2
MyThread t1=new MyThread(); r2
MyThread t2=new MyThread();
t1.start();
t2.start();
System.out.println(t1.isAlive());
System.out.println(t2.isAlive());
}
}
 Example of thread without join() method
public class MyThread extends Thread
{ Output
public void run() r1
{ r1
System.out.println("r1 "); r2
try r2
{
Thread.sleep(500);
} catch(InterruptedException ie) { }
System.out.println("r2 ");
}

17
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

public static void main(String[] args)


{
MyThread t1=new MyThread();
MyThread t2=new MyThread();
t1.start();
t2.start();
}
}
NOTE:-In this above program two thread t1 and t2 are created. t1 starts first and after printing "r1" on console
thread t1 goes to sleep for 500 mls.At the same time Thread t2 will start its process and print "r1" on console
and then goes into sleep for 500 mls. Thread t1 will wake up from sleep and print "r2" on console similarly
thread t2 will wake up from sleep and print "r2" on console. So you will get output like r1 r1 r2 r2
 Example of thread with join() method
public class MyThread extends Thread
{
public void run()
{
System.out.println("r1 "); Output
try r1
{ r2
Thread.sleep(500); r1
} catch(InterruptedException ie) { } r2
System.out.println("r2 "); NOTE:-In this above program join() method on thread
} t1 ensure that t1 finishes it process before thread t2
public static void main(String[] args) starts.
{
MyThread t1=new MyThread();
MyThread t2=new MyThread();
t1.start();
try
{
t1.join(); //Waiting for t1 to finish
} catch(InterruptedException ie){ }
t2.start(); } }

 Specifying time with join()


If in the above program, we specify time while using join() with m1, then m1 will execute for that time, and
thenm2 and m3 will join it.
m1.join(1500);
Doing so, initially m1 will execute for 1.5 seconds, after which m2 and m3 will join it.
 The join() method waits for a thread to die. In other words, it causes the currently running threads to
stop executing until the thread it joins with completes its task.
 Syntax:
• public void join()throws InterruptedException
• public void join(long milliseconds)throws InterruptedException

18
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 Example of join() method


class TestJoinMethod1 extends Thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
try
{
Thread.sleep(500); }
catch(Exception e)
{ Output:
System.out.println(e); 1
} 2
System.out.println(i); 3
} 4
} 5
public static void main(String args[]) 1
{ 1
TestJoinMethod1 t1=new TestJoinMethod1(); 2
TestJoinMethod1 t2=new TestJoinMethod1(); 2
TestJoinMethod1 t3=new TestJoinMethod1(); 3
t1.start(); 3
try 4
{ 4
t1.join(); 5
} 5
catch(Exception e)
{
System.out.println(e);
}
t2.start();
t3.start();
}
}
NOTE:- in the above example,when t1 completes its task then t2 and t3 starts executing.
 Example of join(long miliseconds) method
class TestJoinMethod2 extends Thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
try
{
Thread.sleep(500);
}

19
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

catch(Exception e)
{ Output:
System.out.println(e); 1
} 2
System.out.println(i); 3
} 1
} 4
public static void main(String args[]) 1
{ 2
TestJoinMethod2 t1=new TestJoinMethod2(); 5
TestJoinMethod2 t2=new TestJoinMethod2(); 2
TestJoinMethod2 t3=new TestJoinMethod2(); 3
t1.start(); 3
try 4
{ 4
t1.join(1500); 5
} 5
catch(Exception e)
{
System.out.println(e);
}
t2.start();
t3.start();
}
}
NOTE:- In the above example,when t1 is completes its task for 1500 miliseconds(3 times) then t2 and t3
starts executing.
 A thread invokes the join() method on another thread in order to wait for the other thread to
complete its execution.Consider a thread t1 invokes the method join() on a thread t2. The join() call
has no effect if thread t2 has already completed. If thread t2 is still alive, then thread t1 transits to
the Blocked-for-join-completion state.
• Below is a program showing how threads invoke the overloaded thread join method.
public class ThreadJoinDemo
{
public static void main(String[] args)
{
Thread t1 = new Thread("T1");
Thread t2 = new Thread("T2");
try
{
System.out.println("Wait for the child threads to finish.");
t1.join();
if (!t1.isAlive())
{
System.out.println("Thread T1 is not alive.");
}
t2.join();

20
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

if (!t2.isAlive())
{
System.out.println("Thread T2 is not alive.");
}
}
catch (InterruptedException e)
Output
{
Wait for the child threads to finish.
System.out.println("Main Thread interrupted.");
Thread T1 is not alive.
}
Thread T2 is not alive.
System.out.println("Exit from Main Thread.");
Exit from Main Thread
}
}

21
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

THREAD STATES
A Java thread is always in one of several states which could be running, sleeping, dead, etc.
• A thread can be in any of the following states:
 New Thread state (Ready-to-run state)
 Runnable state (Running state)
 Not Runnable state
 Dead state
 NEW THREAD
A thread is in this state when the instantiation of a Thread object creates a new thread but does not
start it running. A thread starts life in the Ready-to-run state. You can call only the start() or stop()
methods when the thread is in this state. Calling any method besides start() or stop() causes an
IllegalThreadStateException.
 RUNNABLE
When the start() method is invoked on a New Thread() it gets to the runnable state or running state by
calling the run() method. A Runnable thread may actually be running, or may be awaiting its turn to run.
 NOT RUNNABLE
A thread becomes Not Runnable when one of the following four events occurs:
 When sleep() method is invoked and it sleeps for a specified amount of time
 When suspend() method is invoked
 When the wait() method is invoked and the thread waits for notification of a free resource or waits for
the completion of another thread or waits to acquire a lock of an object.
• The thread is blocking on I/O and waits for its completion
• Example: Thread.currentThread().sleep(1000);
• Note: Thread.currentThread() may return an output like Thread[threadA,5,main]
• The SleepMessages example uses sleep to print messages at four-second intervals:

public class SleepMessages


{
public static void main(String args[]) throws InterruptedException
{
String importantInfo[] = { "Mares eat oats","Does eat oats", "Little lambs eat ivy", "A kid will eat ivy too"};
for (int i = 0; i < importantInfo.length;i++)
{
//Pause for 4 seconds OUTPUT
Thread.sleep(4000); the name of the thread,
//Print a message the priority of the thread, and
System.out.println(importantInfo[i]); the name of the group to which it belongs.
}
}
}
NOTE:-Notice that main declares that it throws InterruptedException. This is an exception that sleep throws
when another thread interrupts the current thread while sleep is active. Since this application has not defined
another thread to cause the interrupt, it doesn't bother to catch InterruptedException.

22
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 SOME IMPORTANT POINTS:-


• Here, the run() method put itself to sleep for one second and becomes Not Runnable during that
period.
A thread can be awakened abruptly by invoking the interrupt() method on the sleeping thread object
or at the end of the period of time for sleep is over. Whether or not it will actually start running
depends on its priority and the availability of the CPU.
• Hence I hereby list the scenarios below to describe how a thread switches form a non runnable to a
runnable state:
• If a thread has been put to sleep, then the specified number of milliseconds must elapse (or it must be
interrupted).
• If a thread has been suspended, then its resume() method must be invoked
• If a thread is waiting on a condition variable, whatever object owns the variable must relinquish it by
calling
either notify() or notifyAll().
• If a thread is blocked on I/O, then the I/O must complete.

 DEAD STATE
A thread enters this state when the run() method has finished executing or when the stop() method is
invoked. Once in this state, the thread cannot ever run again.

23
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 THREAD CLASS
 The Thread class defines a number of methods useful for thread management. These
include static methods, which provide information about, or affect the status of, the thread invoking
the method. The other methods are invoked from other threads involved in managing the thread
and Thread object.
 The Thread class defines a number of methods useful for thread management. These
include static methods, which provide information about, or affect the status of, the thread invoking
the method. The other methods are invoked from other threads involved in managing the thread
and Thread object.
 Pausing Execution with Sleep
Thread.sleep causes the current thread to suspend execution for a specified period. This is an efficient means
of making processor time available to the other threads of an application or other applications that might be
running on a computer system. The sleep method can also be used for pacing, as shown in the example that
follows, and waiting for another thread with duties that are understood to have time requirements.

 Two overloaded versions of sleep are provided:


• One that specifies the sleep time to the millisecond and one that specifies the sleep time to the
nanosecond.
• These sleep times are not guaranteed to be precise, because they are limited by the facilities provided
by the underlying OS.

24
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 INTERRUPTS
Thread interruption in java is a mechanism in which a thread which is either sleeping or waiting can be made
to stop sleeping or waiting. Thread interruption is like telling the thread that it should stop waiting or sleeping
and return to running status. Thread interruption is programmatically implemented usinginterrupt() method
of java.lang.Thread class. interrupt() method is a non-static public method of Thread class. Here is the method
signature of interrupt() method.

If any thread is in sleeping or waiting state (i.e. sleep() or wait() is invoked), calling the interrupt() method on
the thread, breaks out the sleeping or waiting state throwing InterruptedException. If the thread is not in the
sleeping or waiting state, calling the interrupt() method performs normal behaviour and doesn't interrupt the
thread but sets the interrupt flag to true. Let's first see the methods provided by the Thread class for thread
interruption.
An interrupt is an indication to a thread that it should stop what it is doing and do something else. It's up
to the programmer to decide exactly how a thread responds to an interrupt, but it is very common for the
thread to terminate. This is the usage emphasized in this lesson.
A thread sends an interrupt by invoking interrupt on the Thread object for the thread to be interrupted.
For the interrupt mechanism to work correctly, the interrupted thread must support its own interruption.
 The 3 methods provided by the Thread class for interrupting a thread
• public void interrupt()
• public static boolean interrupted()
• public boolean isInterrupted()
 Example of interrupting a thread that stops working
• In this example, after interrupting the thread, we are propagating it, so it will stop working. If we don't
want to stop the thread, we can handle it where sleep() or wait() method is invoked. Let's first see the
example where we are propagating the exception.
class TestInterruptingThread1 extends Thread
{
public void run()
{
try
{
Thread.sleep(1000);
System.out.println("task");
}
catch(InterruptedException e)
{
throw new RuntimeException("Thread interrupted..."+e);
}
}

public static void main(String args[])

25
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

{
TestInterruptingThread1 t1=new TestInterruptingThread1();
t1.start();
try Output:
{ Exception in thread-0
t1.interrupt(); java.lang.RuntimeException: Thread interrupted...
} java.lang.InterruptedException: sleep interrupted
catch(Exception e) at A.run(A.java:7)
{
System.out.println("Exception handled "+e);
}
}
}
 Here is an example for interrupting a sleeping thread using interrupt()
method.
public class ThreadsInJava
{
public static void main(String[] args)
{
Thread t = new Thread()
{
public void run()
{
try
{
Thread.sleep(10000); //Thread is sleeping for 10 seconds
}
catch (InterruptedException e)
{
System.out.println("Thread is interrupted");
}
}
}
t.start();
try
{
Thread.sleep(3000); //Main thread is sleeping for 3 seconds
}
catch (InterruptedException e)
{
e.printStackTrace();
}
t.interrupt(); //main thread is interrupting thread t
}
}

EXPLAIN:-

26
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

In the above example, main thread is creating and starting thread t. Thread t is going to sleep for 10 seconds
as soon as it started. main thread, after starting thread t, is also going to sleep for 3 seconds. After sleeping for
3 seconds, main thread calls interrupt() method on thread t. It interrupts sleeping thread t. It causes the
InterruptedException.
 Example of interrupting a thread that doesn't stop working
• In this example, after interrupting the thread, we handle the exception, so it will break out the
sleeping but will not stop working.
class TestInterruptingThread2 extends Thread
{
public void run()
{
try
{
Output:
Thread.sleep(1000);
Exception handled
System.out.println("task");
java.lang.InterruptedException: sleep interrupted
}
thread is running...
catch(InterruptedException e)
{
System.out.println("Exception handled "+e);
}
System.out.println("thread is running...");
}
public static void main(String args[])
{
TestInterruptingThread2 t1=new TestInterruptingThread2();
t1.start();
t1.interrupt();
}
}
 Example of interrupting thread that behaves normally
If thread is not in sleeping or waiting state, calling the interrupt() method sets the interrupted flag to true that
can be used to stop the thread by the java programmer.
class TestInterruptingThread3 extends Thread{
public void run()
{
for(int i=1;i<=5;i++)
{ Output:
System.out.println(i); 1
} 2
} 3
public static void main(String args[]) 4
{ 5
TestInterruptingThread3 t1=new TestInterruptingThread3();
t1.start();
t1.interrupt();
} }

27
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 What about isInterrupted and interrupted method?


• The isInterrupted() method returns the interrupted flag either true or false. The static interrupted()
method returns the interrupted flag afterthat it sets the flag to false if it is true.
public class TestInterruptingThread4 extends Thread
{
public void run()
{
for(int i=1;i<=2;i++)
{
if(Thread.interrupted())
{
System.out.println("code for interrupted thread");
}
else Output:
{ code for interrupted thread
System.out.println("code for normal thread"); code for normal thread
} code for normal thread
}//end of for loop code for normal thread
}
public static void main(String args[])
{
TestInterruptingThread4 t1=new TestInterruptingThread4();
TestInterruptingThread4 t2=new TestInterruptingThread4();
t1.start();
t1.interrupt();
t2.start();
}
}
 This method returns current interrupt status of a thread.
public class ThreadsInJava
{
public static void main(String[] args)
{
Thread t = new Thread()
{
public void run()
{
System.out.println(isInterrupted()); //Output : true

try
{
Thread.sleep(10000); //Thread is going to sleep for 10 seconds
}
catch (InterruptedException e)
{
System.out.println("Thread is interrupted");
}

28
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

System.out.println(isInterrupted()); //Output : false


}
}
t.start();
t.interrupt(); //main thread is interrupting thread t
}
}
NOTE:-Interrupted thread will not be eligible to go for sleep. i.e If you call interrupt() method on a thread
which is not yet slept but running, such thread will throw InterruptedException while going to sleep.
 At the below example. In this example, thread t is interrupted by main thread as soon
as it is started. But thread t will not throw interruptedexception as soon as it is
interrupted. Instead it will continue to print 1000 numbers. While going to sleep after
printing the numbers it will raise interruptedexception.
public class ThreadsInJava
{
public static void main(String[] args)
{
Thread t = new Thread()
{
public void run()
{
for(int i = 0; i <= 1000; i++)
{
System.out.println(i);
}
try
{
Thread.sleep(10000); //Thread is going to sleep for 10 seconds
}
catch (InterruptedException e)
{
System.out.println("Thread is interrupted");
}
}
}
t.start();
t.interrupt(); //main thread is interrupting thread t
}
}

 There is one more method to check interrupt status of a thread,


called interrupted() method. It is a static method of Thread class. It also returns the
29
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

current interrupt status of a thread like isInterrupted() method. But, it clears interrupt
status of a thread. i.e if interrupt status of a thread is true, then it will set the status to
false.
public class ThreadsInJava
{
public static void main(String[] args)
{
Thread t = new Thread()
{
public void run()
{
System.out.println(interrupted()); //Output : false
interrupt();
System.out.println(interrupted()); //Output : true
System.out.println(interrupted()); //Output : false
}
}
t.start();
}
}
NOTE:-interrupt() method will throw SecurityException if current thread can not interrupt a calling thread.
 A thread can interrupt itself. i.e a thread can call interrupt() method on it’s own.
public class ThreadsInJava
{
public static void main(String[] args)
{
Thread t = new Thread()
{
public void run()
{
System.out.println(isInterrupted()); //Output : false
interrupt(); //Thread interrupting itself
System.out.println(isInterrupted()); //Output : true
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
System.out.println("Thread interrupted");
}
System.out.println(isInterrupted()); //Output : false
}
}
t.start();
} }

 Supporting Interruption
30
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

• How does a thread support its own interruption?


This depends on what it's currently doing. If the thread is frequently invoking methods that
throw InterruptedException, it simply returns from the run method after it catches that exception. For
example, suppose the central message loop in the SleepMessages example were in the run method of a
thread's Runnableobject.
 Then it might be modified as follows to support interrupts:
for (int i = 0; i < importantInfo.length; i++)
{
// Pause for 4 seconds // Print a message
try System.out.println(importantInfo[i]);
{ }
Thread.sleep(4000);
} catch (InterruptedException e)
{
// We've been interrupted: no more messages.
return;
}
NOTE:-Many methods that throw InterruptedException, such as sleep, are designed to cancel their current
operation and return immediately when an interrupt is received.
 What if a thread goes a long time without invoking a method that throws InterruptedException?
Then it must periodically invoke Thread.interrupted, which returns true if an interrupt has been received.
• For example:
for (int i = 0; i < inputs.length; i++)
{
heavyCrunch(inputs[i]);
if (Thread.interrupted())
{
// We've been interrupted: no more crunching.
return;
}
}
NOTE:-In this simple example, the code simply tests for the interrupt and exits the thread if one has been
received. In more complex applications,
• it might make more sense to throw an InterruptedException:
if (Thread.interrupted())
{
throw new InterruptedException();
}
• This allows interrupt handling code to be centralized in a catch clause.

 The Interrupt Status Flag


31
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

• The interrupt mechanism is implemented using an internal flag known as the interrupt status.
Invoking Thread.interrupt sets this flag. When a thread checks for an interrupt by invoking the static
method Thread.interrupted, interrupt status is cleared. The non-static isInterrupted method, which is
used by one thread to query the interrupt status of another, does not change the interrupt status flag.
• By convention, any method that exits by throwing an InterruptedException clears interrupt status
when it does so. However, it's always possible that interrupt status will immediately be set again, by
another thread invoking interrupt.
• The join method allows one thread to wait for the completion of another. If t is a Thread object whose
thread is currently executing, t.join(); causes the current thread to pause execution until t's thread
terminates. Overloads of join allow the programmer to specify a waiting period. However, as
with sleep, join is dependent on the OS for timing, so you should not assume that join will wait exactly
as long as you specify.Like sleep, join responds to an interrupt by exiting with an InterruptedException.
• The whole thread interruption mechanism depends on an internal flag called interrupt status. The
initial value of this flag for any thread is false. When you call interrupt() method on a thread, interrupt
status of that thread will be set to true. When a thread throws InterruptedException, this status will be
set to false again. Remember, InterruptedException is thrown when a thread is interrupted while it is
sleeping or waiting. Many methods of Thread class like sleep(), wait(), join() throw
InterruptedException.
 PAUSING EXECUTION WITH SLEEP
Thread.sleep causes the current thread to suspend execution for a specified period. This is an efficient means
of making processor time available to the other threads of an application or other applications that might be
running on a computer system. The sleep method can also be used for pacing, as shown in the example that
follows, and waiting for another thread with duties that are understood to have time requirements.
Two overloaded versions of sleep are provided: one that specifies the sleep time to the millisecond and one
that specifies the sleep time to the nanosecond. However, these sleep times are not guaranteed to be precise,
because they are limited by the facilities provided by the underlying OS. Also, the sleep period can be
terminated by interrupts.

 In any case, you cannot assume that invoking sleep will suspend the thread for
precisely the time period specified Thread Methods:
• FOLLOWING IS THE LIST OF IMPORTANT METHODS AVAILABLE IN THE THREAD CLASS.
32
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

METHODS WITH DESCRIPTION


public void start():Starts the thread in a separate path of execution, then invokes
the run() method on this Thread object, so. It starts the execution of the thread.
JVM calls the run() method on the thread.

public void run():If this Thread object was instantiated using a separate Runnable
target, the run() method is invoked on that Runnable object, so,it is used to perform
action for a thread.

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

public void sleep(long miliseconds): Causes the currently executing thread to sleep
(temporarily cease execution) for the specified number of milliseconds.

public static void sleep(long millisec):Causes the currently running thread to block
for at least the specified number of milliseconds.

public void yield(): causes the currently executing thread object to temporarily
pause and allow other threads to execute.

public static void yield():Causes the currently running thread to yield to any other
threads of the same priority that are waiting to be scheduled.

public void resume(): is used to resume the suspended thread(deprecated).

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

public final void join(long millisec):The current thread invokes this method on a
second thread, causing the current thread to block until the second thread
terminates or the specified number of milliseconds passes.

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

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

public final void setName(String name):Changes the name of the Thread object.
There is also a getName() method for retrieving the name.

public final void setPriority(int priority):Sets the priority of this Thread object. The
possible values are between 1 and 10.

public final void setDaemon(boolean on):A parameter of true denotes this Thread
as a daemon thread.

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

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

33
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

public Thread currentThread(): returns the reference of currently executing thread.

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

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

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

public void interrupt():Interrupts this thread, causing it to continue execution if it


was blocked for any reason.

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

public final boolean isAlive()/public boolean isAlive(): Returns true if the thread is
alive, which is any time after the thread has been started but before it runs to
completion and so used for tests if the thread is alive.

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

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

public static boolean holdsLock(Object x):Returns true if the current thread holds
the lock on the given Object.

public static Thread currentThread():Returns a reference to the currently running


thread, which is the thread that invokes this method.

public static void dumpStack():Prints the stack trace for the currently running
thread, which is useful when debugging a multithreaded application.

 The currentThread() method:


The currentThread() method returns a reference to the currently executing thread object.
• Syntax of currentThread() method:

34
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 public static Thread currentThread(): returns the reference of currently running thread.
• Example of currentThread() method:
class TestMultiNaming2 extends Thread
{
public void run()
{
System.out.println(Thread.currentThread().getName());
}
}
public static void main(String args[])
{
TestMultiNaming2 t1=new TestMultiNaming2();
TestMultiNaming2 t2=new TestMultiNaming2();
t1.start();
t2.start();
}
}
Output:
Thread-0
Thread-1

 So, 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 methods of Thread class:
 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.
• Who makes your class object as thread object?
Thread class constructor allocates a new thread object.When you create object of Multi class,your class
constructor is invoked(provided by Compiler) fromwhere Thread class constructor is invoked(by super() as first
statement).

THREAD LIFE CYCLE OR THREAD STATES IN JAVA


 THERE ARE SIX THREAD STATES.
• They are

35
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 NEW,
 RUNNABLE,
 BLOCKED,
 WAITING,
 TIMED_WAITING
 TERMINATED.
• java.lang.Thread class has one member of enum type called State.
• All states of a thread are stored in this enum as constants.
EXECUTE THE BELOW PROGRAM, IT PRINTS ALL STATES OF A THREAD.
public class ThreadsInJava
{ The output of this program will be,
public static void main(String[] args) NEW
{ RUNNABLE
Thread.State[] states = Thread.State.values(); BLOCKED
WAITING
for (Thread.State state : states) TIMED_WAITING
{ TERMINATED
System.out.println(state);
}
}
}

36
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 SIX STATES OF A JAVA THREAD


• THREAD LIFE SYCLE PROPERTIES:-
The start method creates the system resources, necessary to run the thread, schedules the thread to run, and
calls the thread’s run method.
• A thread becomes “Not Runnable” when one of these events occurs:
 If sleep method is invoked.
 The thread calls the wait method.
 The thread is blocking on I/O.
 A thread dies naturally when the run method exits.

37
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

BELOW DIAGRAM CLEARLY DEPICTS THE VARIOUS PHASES OF THREAD LIFE CYCLE IN JAVA.

1) NEW
A thread will be in this state before calling start() method.
public class JavaThreadLifeCycle
{
public static void main(String[] args)
{
Thread t = new Thread();
//Checking the state before starting the thread
System.out.println(t.getState()); //Output : NEW
}
}
2) RUNNABLE
A thread will be in this state after calling the start() method.
public class JavaThreadLifeCycle
{
public static void main(String[] args)
{
Thread t = new Thread();
t.start();
//Checking the state after starting the thread
System.out.println(t.getState()); //Output : RUNNABLE
}
}
3) BLOCKED
38
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

A thread will be in this state when a thread is waiting for object lock to enter into synchronized
method/block or a thread will be in this state if deadlock occurs.
• Below example shows the states of two threads when deadlock occurs.
class Shared
{
synchronized void methodOne(Shared s)
{
try
{
Thread.sleep(2000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
s.methodTwo(this);
}
synchronized void methodTwo(Shared s)
{
try
{
Thread.sleep(2000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
s.methodOne(this);
}
}
public class ThreadsInJava
{
public static void main(String[] args)
{
final Shared s1 = new Shared();
final Shared s2 = new Shared();
Thread t1 = new Thread()
{
public void run()
{
s1.methodOne(s2);
}
}

Thread t2 = new Thread()

39
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

{
public void run()
{
s2.methodTwo(s1);
}
}
t1.start();
t2.start();
try
{
Thread.sleep(3000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
//Checking states of both the threads
System.out.println(t1.getState()); //Output : BLOCKED
System.out.println(t2.getState()); //Output : BLOCKED
}
}
4) WAITING
A thread will be in this state when wait() or join() method is called. Below example shows the thread state
when join() method is called.
public class ThreadsInJava
{
public static void main(String[] args)
{
final Thread t1 = new Thread()
{
public void run()
{
try
{
Thread.sleep(2000);
}

catch (InterruptedException e)
{
e.printStackTrace();
}
}
}

Thread t2 = new Thread()


{
40
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

public void run()


{
try
{
t1.join();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
t2.start();
t1.start();
try
{
Thread.sleep(100);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
//Checking the state of t2 after it calls join() on t1
System.out.println(t2.getState()); //Output : WAITING
} }
5) TIMED_WAITING
A thread will be in this state when thread is sleeping. i.e A thread will be in this state when sleep() or wait()
with timeOut or join() with timeOut is called.
public class ThreadsInJava
{
public static void main(String[] args)
{
Thread t = new Thread()
{
public void run()
{
try
{
Thread.sleep(5000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}

t.start();
try
41
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

{
Thread.sleep(2000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
//Checking the state when thread is sleeping
System.out.println(t.getState()); //Output : TIMED_WAITING
}
}
6) TERMINATED
A thread will be in this state once it finishes it’s execution.
public class ThreadsInJava
{
public static void main(String[] args)
{
Thread t = new Thread()
{
public void run()
{
for(int i = 0; i <= 25; i++)
{
System.out.println(i);
} } };
t.start();
try
{
Thread.sleep(2000); //Main thread is sleeping for 2 sec
}
catch (InterruptedException e)
{
e.printStackTrace();
}
//Checking the state when thread t is finished it's execution
System.out.println(t.getState()); //Output : TERMINATED
}
}

42
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 ABOVE-MENTIONED STAGES ARE EXPLAINED HERE:


 New: A new thread begins its life cycle in the new state. It remains in this state until the program starts
the thread. It is also referred to as a born thread.
 Runnable: After a newly born thread is started, the thread becomes runnable. A thread in this state is
considered to be executing its task.
 Waiting: Sometimes, a thread transitions to the waiting state while the thread waits for another thread
to perform a task. A thread transitions back to the runnable state only when another thread signals the
waiting thread to continue executing.
 Timed waiting: A runnable thread can enter the timed waiting state for a specified interval of time. A
thread in this state transitions back to the runnable state when that time interval expires or when the
event it is waiting for occurs.
 Terminated ( Dead ): A runnable thread enters the terminated state when it completes its task or
otherwise terminates.

43
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 THREAD SCHEDULER
The thread scheduler, part of the OS (usually) that is responsible for sharing the available CPUs out between
the various threads. How exactly the scheduler works depends on the individual platform, but various modern
operating systems (notably Windows and Linux) use largely similar techniques .
Again, the thread scheduler is the part of the JVM that decides which thread should run at any given
moment, and also takes threads out of the run state. Any thread in the runnable state can be chosen by the
scheduler to be the one and only running thread. If a thread is not in a runnable state, then it cannot be
chosen to be the currently running thread. Some method that can influence scheduler to some extent(Note*:
We can’t control the behavior of Thread scheduler).
 Schedulers in JVM implementations usually employ one of the two following
strategies:
• Preemptive scheduling
If a thread with a higher priority than all other Runnable threads becomes Runnable, the scheduler will
preempt the running thread (is moved to the runnable state) and choose the new higher priority thread for
execution.
• Time-Slicing or Round-Robin scheduling
 A running thread is allowed to execute for a fixed length of time (a time slot it’s assigned to), after
which it moves to the Ready-to-run state (runnable) to await its turn to run again.
 A thread scheduler is implementation and platform-dependent; therefore, how threads will be
scheduled is unpredictable across different platforms.
NOTE:-
• On multiprocessor systems, there is generally some kind of scheduler per processor, which then need
to be coordinated in some way. (On some systems, switching on different processors is staggered to
avoid contention on shared scheduling tables.) Unless otherwise specified, we'll use the term thread
scheduler to refer to this overall system of coordinated per-CPU schedulers.
• Thread scheduler in java is the part of the JVM that decides which thread should run.
• There is no guarantee that which runnable thread will be chosen to run by the thread scheduler.
• 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.

 ACROSS PLATFORMS, THREAD SCHEDULING TENDS TO BE BASED ON AT LEAST THE


FOLLOWING CRITERIA:
• a priority, or in fact usually multiple "priority" settings that we'll discuss below;
• a quantum, or number of allocated time slices of CPU, which essentially determines the amount of
CPU time a thread is allotted before it is forced to yield the CPU to another thread of the same or lower
priority (the system will keep track of the remaining quantum at any given time, plus its default
quantum, which could depend on thread type and/or system configuration);
• a state, notably "runnable" vs "waiting";
• the behavior of threads, such as recent CPU usage or the time since it last ran (i.e. had a share of CPU),
or the fact that it has "just received an event it was waiting for".

44
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 Most systems use what might dub priority-based round-robin scheduling to some
extent. The general principles are:
• a thread of higher priority (which is a function of base and local priorities) will preempt a thread of
lower priority;
• otherwise, threads of equal priority will essentially take turns at getting an allocated slice
or quantum of CPU;
• there are a few extra "tweaks" to make things work.
 STATES
Depending on the system, there are various states that a thread can be in. Probably the two most
interesting are:
• runnable, which essentially means "ready to consume CPU"; being runnable is generally
the minimum requirement for a thread to actually be scheduled on to a CPU;
• waiting, meaning that the thread currently cannot continue as it is waiting for a resource such as a lock
or I/O, for memory to be paged in, for a signal from another thread, or simply for a period of time to
elapse (sleep).

 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.
 Sleep method in java
The sleep() method of Thread class is used to sleep a thread for the specified amount of time.
 Syntax of sleep() method in java
• The Thread class provides two methods for sleeping a thread:
 public static void sleep(long miliseconds)throws InterruptedException
 public static void sleep(long miliseconds, int nanos)throws InterruptedException
 Example of sleep method in java
class TestSleepMethod1 extends Thread
{
public void run() Output:
NOTE:-
{ 1
As you know well that at a time only
for(int i=1;i<5;i++) 1 one thread is executed. If you sleep
{ 2
a thread for the specified time,the
try 2
thread scheduler picks up another
{ 3
thread and so on.
Thread.sleep(500); 3
} 4
catch(InterruptedException e) 4
{
System.out.println(e);
}
System.out.println(i);
}
}

45
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

public static void main(String args[])


{
TestSleepMethod1 t1=new TestSleepMethod1();
TestSleepMethod1 t2=new TestSleepMethod1();
t1.start();
t2.start();
}
}
 Can we start a thread twice
No. After starting a thread, it can never be started again. If does so, an IllegalThreadStateException is thrown.
In such case, thread will run once but for second time, it will throw exception.
 The example given below:
public class TestThreadTwice1 extends Thread
{ Output:
public void run() running
{ Exception in thread "main" java.lang.IllegalThreadStateException
System.out.println("running...");
}
public static void main(String args[])
{
TestThreadTwice1 t1=new TestThreadTwice1();
t1.start();
t1.start();
}
}

 What if we call run() method directly instead start() method?


 Each thread starts in a separate call stack.
 Invoking the run() method from main thread, the run() method goes onto the current call stack rather
than at the beginning of a new call stack.
EXAMPLE:-
class TestCallRun1 extends Thread
{
public void run()
{
System.out.println("running..."); Output:
} running
public static void main(String args[])
{
TestCallRun1 t1=new TestCallRun1();
t1.run();//fine, but does not start a separate call stack
}
}

Problem if you direct call run() method


46
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 EXAMPLE:-
class TestCallRun2 extends Thread Output:
{ 1
public void run() 2
{ 3
for(int i=1;i<5;i++) 4
{ 5
try 1
{ 2
Thread.sleep(500); 3
} 4
catch(InterruptedException e) 5
{
System.out.println(e);
}
System.out.println(i);
}
}
public static void main(String args[])
{
TestCallRun2 t1=new TestCallRun2();
TestCallRun2 t2=new TestCallRun2();
t1.run();
t2.run();
}
}

 THESE METHODS ARE FROM THREAD CLASS


1 * public static void sleep(long millis) throws InterruptedException
2 * public static void yield()
3 * public final void join() throws InterruptedException
4 * public final void setPriority(int newPriority)
 METHODS FROM OBJECT CLASS.
1 * public final void wait() throws InterruptedException
2 * public final void notify()
3 * public final void notifyAll()
 CHARACTERISTICS
• Execution of multiple threads on a single CPU, in some order, is called scheduling.
• In general, the runnable thread with the highest priority is active (running)
• Java is priority-preemptive
• If a high-priority thread wakes up, and a low-priority thread is running
• Then the high-priority thread gets to run immediately
• Allows on-demand processing
• Efficient use of CPU

47
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 TYPES OF SCHEDULING
• Waiting and Notifying
Waiting [wait()] and notifying [notify(), notifyAll()] provides means of communication between threads that
synchronize on the same object.
• wait(): when wait() method is invoked on an object, the thread executing that code gives up its lock
on the object immediately and moves the thread to the wait state.
• notify(): This wakes up threads that called wait() on the same object and moves the thread to ready
state.
• notifyAll(): This wakes up all the threads that called wait() on the same object.

 Running and Yielding


• Yield() is used to give the other threads of the same priority a chance to execute i.e. causes current
running thread to move to runnable state. It is also static method so it works only on currently running
thread. Scheduler make it sure that If a thread enters the runnable state, and it has a higher priority
than any of the threads in the pool and a higher priority than the currently running thread, the lower-
priority running thread usually will be bumped back to runnable and the highest-priority thread will be
chosen to run. at any given time the currently running thread usually will not have a priority that is
lower than any of the threads in the pool. yield() is supposed to do is make the currently running
thread head back to runnable to allow other threads of the same priority to get their turn.
• Sleeping and Waking up
sleep() is used to pause a thread for a specified period of time i.e. moves the current running thread to Sleep
state for a specified amount of time, before moving it to runnable state. Thread.sleep(no. of milliseconds);
The sleep() method is a static method of class Thread. (where it still has to beg to be the currently running
thread). as it is static method only currently running Thread will sleep.
Syntax would be : Thread.sleep()

 WAITING AND NOTIFYING


• Waiting and notifying provide means of thread inter-communication that synchronizes on the same
object. The threads execute wait() and notify() (or notifyAll()) methods on the shared object for this
purpose. The notifyAll(), notify() and wait() are methods of the Object class. These methods can be
invoked only from within a synchronized context (synchronized method or synchronized block),
otherwise, the call will result in an IllegalMonitorStateException. The notifyAll() method wakes up all
the threads waiting on the resource. In this situation, the awakened threads compete for the resource.
One thread gets the resource and the others go back to waiting.
• wait() method signatures
 final void wait(long timeout) throws InterruptedException
 final void wait(long timeout, int nanos) throws InterruptedException
 final void wait() throws InterruptedException
• The wait() call can specify the time the thread should wait before being timed out. An another thread
can invoke an interrupt() method on a waiting thread resulting in an InterruptedException. This is a
checked exception and hence the code with the wait() method must be enclosed within a try catch
block.

48
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 notify() method signatures


• final void notify()
• final void notifyAll()
A thread usually calls the wait() method on the object whose lock it holds because a condition for its
continued execution was not met. The thread leaves the Running state and transits to the Waiting-for-
notification state. There it waits for this condition to occur. The thread relinquishes ownership of the object
lock. The releasing of the lock of the shared object by the thread allows other threads to run and execute
synchronized code on the same object after acquiring its lock.
The wait() method causes the current thread to wait until another thread notifies it of a condition change.
• A thread in the Waiting-for-notification state can be awakened by the occurrence of any one of these
three incidents:
 Another thread invokes the notify() method on the object of the waiting thread, and the waiting
thread is selected as the thread to be awakened.
 The waiting thread times out.
 Another thread interrupts the waiting thread.
 notify()
Invoking the notify() method on an object wakes up a single thread that is waiting on the lock of this object.
A call to the notify() method has no consequences if there are no threads in the wait set of the object.
The notifyAll() method wakes up all threads in the wait set of the shared object.
• Below program shows three threads, manipulating the same stack. Two of them are pushing
elements on the stack, while the third one is popping elements off the stack. This example illustrates
how a thread waiting as a result of calling the wait() method on an object, is notified by another
thread calling the notify() method on the same object
class StackClass
{
private Object[] stackArray;
private volatile int topOfStack;
StackClass(int capacity)
{
stackArray = new Object[capacity];
topOfStack = -1;
}
public synchronized Object pop()
{
System.out.println(Thread.currentThread() + ": popping");
while (isEmpty())
{
try
{
System.out.println(Thread.currentThread()+ ": waiting to pop");
wait();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
49
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

Object obj = stackArray[topOfStack];


stackArray[topOfStack--] = null;
System.out.println(Thread.currentThread()+ ": notifying after pop");
notify();
return obj;
}
public synchronized void push(Object element)
{
System.out.println(Thread.currentThread() + ": pushing");
while (isFull())
{
try
{
System.out.println(Thread.currentThread()+ ": waiting to push");
wait();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
stackArray[++topOfStack] = element;
System.out.println(Thread.currentThread()+ ": notifying after push");
notify();
}
public boolean isFull()
{
return topOfStack &gt;= stackArray.length - 1;
}
public boolean isEmpty()
{
return topOfStack &lt; 0;
}
}
abstract class StackUser extends Thread
{
protected StackClass stack;
StackUser(String threadName, StackClass stack)
{
super(threadName);
this.stack = stack;
System.out.println(this);
setDaemon(true);
start();
}
}

50
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

class StackPopper extends StackUser // Stack Popper


{
StackPopper(String threadName, StackClass stack)
{
super(threadName, stack);
}
public void run()
{
while (true)
{
stack.pop();
}
}
}
class StackPusher extends StackUser
{
StackPusher(String threadName, StackClass stack) // Stack Pusher
{
super(threadName, stack);
}
public void run()
{
while (true)
{
stack.push(new Integer(1));
}
}
}
public class WaitAndNotifyExample
{
public static void main(String[] args)
{
StackClass stack = new StackClass(5);
new StackPusher("One", stack);
new StackPusher("Two", stack);
new StackPopper("Three", stack);
System.out.println("Main Thread sleeping.");
try
{
Thread.sleep(500);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println("Exit from Main Thread.");
}
}

51
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 Wait Notify methods Thread Program Example


• The field topOfStack in class StackClass is declared volatile, so that read and write operations on this
variable will access the master value of this variable, and not any copies, during runtime.
• Since the threads manipulate the same stack object and the push() and pop() methods in the class
StackClassare synchronized, it means that the threads synchronize on the same object.
How the program uses wait() and notify() for inter thread communication.
(1) The synchronized pop() method – When a thread executing this method on the StackClass object finds that
the stack is empty, it invokes the wait() method in order to wait for some other thread to fill the stack by using
the synchronized push. Once an other thread makes a push, it invokes the notify method.
(2)The synchronized push() method – When a thread executing this method on the StackClass object finds that
the stack is full, i t invokes the wait() method to await some other thread to remove an element to provide
space for the newly to be pushed element.

 Difference Between notify And notifyAll In Java


• notify() and notifyAll() methods along with wait() method are used to establish a communication
between the threads. A thread goes into WAITING mode by calling wait() method. This thread will be in
WAITING state until any other thread calls either notify() or notifyAll() method on the same object. -
threads communicate with each other using wait(), notify() and notifyAll() in Java.
• Any thread calling wait(), notify() andnotifyAll() must have lock of that object. In the other words, these
methods must be called within synchronized method or synchronized block.
 notify() In Java :
When a thread calls notify() method on a particular object, only one thread will be notified which is waiting for
the lock or monitor of that object. The thread chosen to notify is random i.e randomly one thread will be
selected for notification. Notified thread doesn’t get the lock of the object immediately. It gets once
the calling thread releases the lock of that object. Until that it will be in BLOCKED state. It will move from
BLOCKED state to RUNNING state once it gets the lock.
Note : Before notification, the thread will be in WAITING state. Once it is notified, it will
move to BLOCKED state. It remains in BLOCKED state until it gets the lock. Once it gets the
lock, it moves from BLOCKED state to RUNNING state.
 notify() method with an example.
class Shared
{
synchronized void waitMethod()
{
Thread t = Thread.currentThread();
System.out.println(t.getName()+" is releasing the lock and going to wait");
try
{
wait();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println(t.getName()+" has been notified and acquired the lock back");
}

52
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

synchronized void notifyOneThread()


{
Thread t = Thread.currentThread();
notify();
System.out.println(t.getName()+" has notified one thread waiting for this object lock");
}
}
public class MainClass
{
public static void main(String[] args)
{
final Shared s = new Shared();
//Thread t1 will be waiting for lock of object 's'
Thread t1 = new Thread()
{
public void run()
{
s.waitMethod();
}
}
t1.start();
//Thread t2 will be waiting for lock of object 's'
Thread t2 = new Thread()
{
public void run()
{
s.waitMethod();
}
}
t2.start();
//Thread t3 will be waiting for lock of object 's'
Thread t3 = new Thread()
{
public void run()
{
s.waitMethod();
}
}
t3.start();
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}

53
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

//Thread t4 will notify only one thread which is waiting for lock of object 's'
Thread t4 = new Thread()
{ Output :
public void run() Thread-1 is releasing the lock and going to wait
{ Thread-0 is releasing the lock and going to wait
s.notifyOneThread(); Thread-2 is releasing the lock and going to wait
} Thread-3 has notified one thread waiting for this object lock
} Thread-1 has been notified and acquired the lock back
t4.start();
}
}
 notifyAll() In Java :
When a thread calls notifyAll() method on a particular object, all threads which are waiting for the lock of that
object are notified. All notified threads will move from WAITING state to BLOCKED state. All these threads will
get the lock of the object on a priority basis. The thread which gets the lock of the object moves to RUNNING
state. The remaining threads will remain in BLOCKED state until they get the object lock.
• Below is an example of notifyAll() method in Java.
class Shared
{
synchronized void waitMethod()
{
Thread t = Thread.currentThread();
System.out.println(t.getName()+" is releasing the lock and going to wait");
try
{
wait();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println(t.getName()+" has been notified and acquired the lock back");
}
synchronized void notifyAllThread()
{
Thread t = Thread.currentThread();
notifyAll();
System.out.println(t.getName()+" has notified all threads waiting for this object lock");
}
}
public class MainClass
{
public static void main(String[] args)
{
final Shared s = new Shared();
//Thread t1 will be waiting for lock of object 's'

54
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

Thread t1 = new Thread()


{
public void run()
{
s.waitMethod();
}
}
t1.start();
//Thread t2 will be waiting for lock of object 's'
Thread t2 = new Thread()
{
public void run()
{
s.waitMethod();
}
}
t2.start();
//Thread t3 will be waiting for lock of object 's'
Thread t3 = new Thread()
{
public void run() Output :
{ Thread-0 is releasing the lock and going to wait
s.waitMethod(); Thread-2 is releasing the lock and going to wait
} Thread-1 is releasing the lock and going to wait
Thread-3 has notified all threads waiting for this object lock
}
Thread-1 has been notified and acquired the lock back
t3.start();
Thread-2 has been notified and acquired the lock back
try Thread-0 has been notified and acquired the lock back
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
//Thread t4 will notify all threads which are waiting for lock of object 's'
Thread t4 = new Thread()
{
public void run()
{
s.notifyAllThread();
}
}
t4.start();
}
}

55
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 Difference Between notify And notifyAll In Java :


Below diagram summarizes the difference between notify and notifyAll in java.

56
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 DIFFERENCE BETWEEN WAIT() AND SLEEP() FUNCTION:-


 wait() method along with notify() and notifyAll() are used for inter thread communication where as
sleep() method is used to pause the execution of current thread for specific period of time.
 wait() method is an instance method of java.lang.Object class. That means, this method is available in
all objects you create in java. Where as sleep() method is a static method of java.lang.Thread class.
That means, it is available only in threads.
 wait() method is called on objects. Whenever it is called by a thread on a particular object,
thread releases the lock of that object and waits until other threads call either notify() or notifyAll()
methods on the same object. Where as sleep() method is called on threads.
 Whenever sleep() method is called, only current thread is going for sleep. For example, if main thread
calls sleep() method on a thread t, i.e t.sleep(), main thread itself is going to sleep not thread t.
 To call wait() method, calling thread must hold the lock of the object on which it is calling wait()
method. That means, wait() method must be called within the synchronized block. Where as to call
sleep() method, thread need not to hold the object lock. That means, sleep() method can be
called outside the synchronized block also.

wait() sleep()
The thread which calls wait() method The thread which calls sleep() method
releases the lock it holds. doesn’t release the lock it holds.

The thread regains the lock after other


threads call either notify() or notifyAll() No question of regaining the lock as thread
methods on the same lock. doesn’t release the lock.

wait() method must be called within the sleep() method can be called within
synchronized block. or outside the synchronized block.

wait() method is a member of sleep() method is a member of


java.lang.Object class. java.lang.Thread class.

wait() method is always called on objects. sleep() method is always called on threads.

wait() is a non-static method of Object class. sleep() is a static method of Thread class.

Waiting threads can be awake by other Sleeping threads can not be awake by other
threads by calling notify() or notifyAll() threads. If done so, thread will throw
methods. InterruptedException.

To call wait() method, thread must have To call sleep() method, thread need not to
object lock. have object lock.

monitor is released monitor is not released

57
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

58
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 THREAD PRIORITIES:
 Every Java thread has a priority that helps the operating system determine the order in which threads
are scheduled.
 Java thread priorities are in the range between MIN_PRIORITY (a constant of 1) and MAX_PRIORITY
(a constant of 10). By default, every thread is given priority NORM_PRIORITY (a constant of 5). The
higher the integer, the higher the priority. Normally the thread priority will be 5.
 Threads with higher priority are more important to a program and should be allocated processor time
before lower-priority threads. However, thread priorities cannot guarantee the order in which threads
execute and very much platform dependent.
 Thread priorities are the integers which decide how one thread should be treated with respect to the
others.
 Thread priority decides when to switch from one running thread to another, process is called context
switching
 A thread can voluntarily release control and the highest priority thread that is ready to run is given the
CPU.
 A thread can be preempted by a higher priority thread no matter what the lower priority thread is
doing. Whenever a higher priority thread wants to run it does.
 To set the priority of the thread setPriority() method is used which is a method of the
class Thread Class.
 In place of defining the priority in integers, we can
useMIN_PRIORITY, NORM_PRIORITY or MAX_PRIORITY.

 Methods: isAlive() and join()


 In all the practical situations main thread should finish last else other threads which have produced
from the main thread will also finish.
 To know whether the thread has finished we can call isAlive() on the thread which returns true if the
thread is not finished.
 Another way to achieve this by using join() method, this method when called from the parent thread
makes parent thread wait till child thread terminates.
 These methods are defined in the Thread class.

 A Thread ends due to the following reasons:


 The thread ends when it comes when the run() method finishes its execution.
 When the thread throws an Exception or Error that is not being caught in the program.
 Java program completes or ends.
 Another thread calls stop() methods.

59
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 Synchronization of Threads
 In many cases concurrently running threads share data and two threads try to do operations on the
same variables at the same time. This often results in corrupt data as two threads try to operate on the
same data.
 A popular solution is to provide some kind of lock primitive. Only one thread can acquire a particular
lock at any particular time. This can be achieved by using a keyword “synchronized” .
 By using the synchronize only one thread can access the method at a time and a second call will be
blocked until the first call returns or wait() is called inside the synchronized method.
 Each thread have a priority. Priorities are represented by a number between 1 and 10. In most cases,
thread schedular schedules the threads according to their priority (known as preemptive scheduling).
But it is not guaranteed because it depends on JVM specification that which scheduling it chooses.
• 3 constants defiend in Thread class:
 public static int MIN_PRIORITY
 public static int NORM_PRIORITY
 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.
• Example of priority of a Thread:
class TestMultiPriority1 extends Thread
{
public void run()
{
System.out.println("running thread name is:"+Thread.currentThread().getName());
System.out.println("running thread priority is:"+Thread.currentThread().getPriority());
}
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

60
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

Daemon Thread in Java


There are two types of Threads in java.
1) User Thread
2) Daemon Thread
1) User Thread :
User threads are threads which are created by the application or user. They are high priority threads. JVM
(Java Virtual Machine) will not exit until all user threads finish their execution. JVM wait for these threads to
finish their task. These threads are foreground threads.
class UserThread extends Thread
{
public void run()
{
for(int i = 0; i < 1000; i++)
{
System.out.println("This is an user thread....");
}
}
}
public class ThreadsInJava
{
//Main Thread
public static void main(String[] args)
{
UserThread userThread = new UserThread(); //Creating the UserThread
userThread.setDaemon(true); //Changing the thread as Daemon
userThread.start(); //Starting the thread
}
}
Note:- can convert user thread into daemon thread explicitly by calling setDaemon() method
of the thread.

61
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

2) Daemon Thread
• Daemon thread in java is a service provider thread that provides services to the user thread. Its life
depend on the mercy of user threads i.e. when all the user threads dies, JVM terminates this thread
automatically.
• There are many java daemon threads running automatically e.g. gc, finalizer etc.
 Points to remember for Daemon Thread in Java
• It provides services to user threads for background supporting tasks. It has no role in life than to serve
user threads.
• Its life depends on user threads.
• It is a low priority thread.

 What is Daemon Thread in Java?


Daemon threads in Java are like a service providers for other threads or objects running in the same process as
the daemon thread. Daemon threads are used for background supporting tasks and are only needed while
normal threads are executing. If normal threads are not running and remaining threads are daemon threads
then the interpreter exits.
When a new thread is created it inherits the daemon status of its parent. Normal thread and daemon
threads differ in what happens when they exit. When the JVM halts any remaining daemon threads are
abandoned: finally blocks are not executed, stacks are not unwound – JVM just exits. Due to this reason
daemon threads should be used sparingly and it is dangerous to use them for tasks that might perform any
sort of I/O.
 setDaemon(true/false) ?
• This method is used to specify that a thread is daemon thread.
• Syntax:- public boolean isDaemon() ?
Note:-
 This method is used to determine the thread is daemon thread or not.
 Daemon thread in Java are those thread which runs in background and mostly created by JVM for
performing background task like Garbage collection and other house keeping tasks.
 Any thread created by main thread, which runs main method in Java is by default non daemon because
Thread inherits its daemon nature from the Thread which creates it i.e. parent Thread and since main
thread is a non daemon thread, any other thread created from it will remain non-daemon until
explicitly made daemon by calling setDaemon(true).
 Thread.setDaemon(true) makes a Thread daemon but it can only be called before starting Thread in
Java. It will throw IllegalThreadStateException if corresponding Thread is already started and running.

62
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 Java makes a distinction between a user thread and another type of thread known as
a daemon thread.
 The daemon threads are typically used to perform services for user threads. The main() method of the
application thread is a user thread. Threads created by a user thread are user thread. JVM doesn't
terminates unless all the user thread terminate.
 User can explicitly specify a thread created by a user thread to be a daemon thread by calling
setDaemon(true) on a Thread object. For example, the clock handler thread, the idle thread, the
garbage collector thread, the screen updater thread, and the garbage collector thread are all daemon
threads. A new created thread inherits the "daemon-status" of the thread that created it unless you
explicitly calling setDaemon on that Thread object to change its status.
 the setDaemon() method must be called before the thread's start() method is invoked.Once a thread
has started executing (i.e., its start() method has been called) its daemon status cannot be changed. To
determine if a thread is a daemon thread, use the accessor method isDaemon().

 The difference between these two types of threads is straightforward:


If the Java runtime determines that the only threads running in an application are daemon threads (i.e., there
are no user threads in existence) the Java runtime promptly closes down the application, effectively stopping
all daemon threads dead in their tracks. In order for an application to continue running, it must always have at
least one live user thread. In all other respects the Java runtime treats daemon threads and user threads in
exactly the same manner.
 set a daemon property after starting the thread. If you try to set the daemon property when the
thread is active, It will throw a IllegalThreadStateException at run time.
class UserThread extends Thread
{
public void run()
{
for(int i = 0; i < 1000; i++)
{
System.out.println("This is an user thread....");
}
}
}
public class ThreadsInJava
{
public static void main(String[] args)
{
UserThread userThread = new UserThread(); //Creating the UserThread
userThread.start(); //Starting the thread
userThread.setDaemon(true); //This statement will throw IllegalThreadStateException
}
}

 whether the thread is user thread or a daemon thread by using isDaemon() method of
Thread class. This method returns “true” for a daemon thread and “false” for a user
thread.
63
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

class UserThread extends Thread


{
public void run()
{
for(int i = 0; i < 1000; i++)
{
System.out.println("This is an user thread....");
}
}
}
public class ThreadsInJava
{
public static void main(String[] args)
{
UserThread userThread = new UserThread(); //Creating the UserThread
System.out.println(userThread.isDaemon()); //Output : false
userThread.setDaemon(true); //changing the thread as Daemon
userThread.start(); //Starting the thread
System.out.println(userThread.isDaemon()); //Output : true
}
}
 Daemon property of a thread is inherited from it’s parent thread. i.e The thread
created by user thread will be user thread and the thread created by daemon thread
will be a daemon thread.
class Thread1 extends Thread
{
public void run()
{
Thread t = new Thread(); //Creating a child thread
System.out.println(t.isDaemon()); //Checking the Daemon property of a child thread
}
}
public class ThreadsInJava
{
public static void main(String[] args)
{
Thread1 t1 = new Thread1(); //Creating the Thread1
t1.start(); //Starting the thread
Thread1 t2 = new Thread1(); //Creating the Thread1
t2.setDaemon(true); //changing the thread as Daemon
t2.start(); //Starting the thread
}
}
 The main thread or primary thread created by JVM is an user thread.
• Demonstration of User thread and daemon thread : In the below program, The task
of daemon thread will not be completed. Program terminates as soon as user thread
finishes it’s task. It will not wait for daemon thread to finish it’s task.
64
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

class UserThread extends Thread


{
public void run()
{
System.out.println("This is a user thread.....");
}
}
class DaemonThread extends Thread
{
public DaemonThread()
{
setDaemon(true);
}
public void run()
{
for(int i = 0; i < 1000; i++)
{
System.out.println("This is daemon thread....."+i);
}
}
}
public class ThreadsInJava
{
public static void main(String[] args)
{
DaemonThread daemon = new DaemonThread(); //Creating the DaemonThread
daemon.start(); //Starting the daemon thread
UserThread userThread = new UserThread(); //Creating the UserThread
userThread.start(); //Starting the user thread
}
}

 Why JVM terminates the daemon thread if there is no user thread?


The sole purpose of the daemon thread is that it provides services to user thread for background supporting
task. If there is no user thread, why should JVM keep running this thread. That is why JVM terminates the
daemon thread if there is no user thread.

 Methods for Java Daemon thread by Thread class


The java.lang.Thread class provides two methods for java daemon thread.
Method Description
65
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

public void setDaemon(boolean is used to mark the current thread as daemon thread or
status) user thread.
public boolean isDaemon() is used to check that current is daemon.

 Simple example of Daemon thread in java


• File: MyThread.java
public class TestDaemonThread1 extends Thread
{
public void run()
{
if(Thread.currentThread().isDaemon())//checking for daemon thread
{
System.out.println("daemon thread work");
}
else
{
System.out.println("user thread work");
}
}
public static void main(String[] args)
{
TestDaemonThread1 t1=new TestDaemonThread1();//creating thread
TestDaemonThread1 t2=new TestDaemonThread1();
TestDaemonThread1 t3=new TestDaemonThread1();
t1.setDaemon(true);//now t1 is daemon thread
t1.start();//starting threads
t2.start();
t3.start();
}
}
Output
daemon thread work
user thread work
user thread work

 To make a user thread as Daemon, it must not be started otherwise it will throw
illegalthreadstateexception.
• File: MyThread.java
class TestDaemonThread2 extends Thread
{
public void run()
66
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

{
System.out.println("Name: "+Thread.currentThread().getName());
System.out.println("Daemon: "+Thread.currentThread().isDaemon());
}
public static void main(String[] args)
{
TestDaemonThread2 t1=new TestDaemonThread2();
TestDaemonThread2 t2=new TestDaemonThread2();
t1.start();
t1.setDaemon(true);//will throw exception here
t2.start();
}
}
Output: exception in thread main: java.lang.IllegalThreadStateException

 Example:
public class CrunchifyDaemonThread extends Thread
{
public static void main(String[] args)
{
System.out.println("Main Method Entry");
CrunchifyDaemonThread t = new CrunchifyDaemonThread();
t.setDaemon(true);
// When false, (i.e. when it's a user thread), the Worker thread
// continues to run.
// When true, (i.e. when it's a daemon thread), the Worker thread
// terminates when the main thread terminates.
t.start();
try
{
Thread.sleep(3000);
}
catch (InterruptedException x)
{}
System.out.println("Main Method Exit");
}
public void run()
{
System.out.println("run Method Entry");
try
{
System.out.println("In run Method: currentThread() is"+ Thread.currentThread());
while (true)
{
try
{
Thread.sleep(1000);
}

67
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

catch (InterruptedException x)
{ }
System.out.println("In run method.." + Thread.currentThread());
}
}
finally
{
System.out.println("run Method Exit");
}
}
}
Output1: (with t.setDaemon(true)):
with t.setDaemon(true);
Main Method Entry
run Method Entry
In run Method: currentThread() isThread[Thread-0,5,main]
In run method..Thread[Thread-0,5,main]
In run method..Thread[Thread-0,5,main]
Main Method Exit
Output2: (with t.setDaemon(false)):
with t.setDaemon(false);
Main Method Entry
run Method Entry
In run Method: currentThread() isThread[Thread-0,5,main]
In run method..Thread[Thread-0,5,main]
In run method..Thread[Thread-0,5,main]
Main Method Exit
In run method..Thread[Thread-0,5,main]
In run method..Thread[Thread-0,5,main]
In run method..Thread[Thread-0,5,main]
In run method..Thread[Thread-0,5,main]
...
...
...

 EXAMPLE:-
public class DaemonThreadExample
{
public static void main(String args[])
{
Thread daemonThread = new Thread(new Runnable()
68
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

{
public void run()
{
try
{
while(true)
{
System.out.println("Daemon thread is running");
}
}
catch(Exception e)
{ }
Finally
{
System.out.println("Daemon Thread exiting"); //never called
}
}
}
daemonThread.setDaemon(true); //making this thread daemon
daemonThread.start();
}
Output:
Daemon thread is running
Daemon thread is running
Daemon thread is running
Daemon thread is running
Daemon thread is running
Daemon thread is running
Daemon thread is running
Daemon thread is running

 Important points about Daemon threads in Java


1. Any thread created by main thread, which runs main method in Java is by default non daemon
because Thread inherits its daemon nature from the Thread which creates it i.e. parent Thread and since
main thread is a non daemon thread, any other thread created from it will remain non-daemon until
explicitly made daemon by calling setDaemon(true).
2. Thread.setDaemon(true) makes a Thread daemon but it can only be called before starting Thread in
Java. It will throw IllegalThreadStateException if corresponding Thread is already started and running.
3. Daemon Threads are suitable for doing background jobs like housekeeping, Though I have yet to use it
for any practical purpose in application code. let us know if you have used daemon thread in your java
application for any practical purpose.

 Difference Between User Threads Vs Daemon Threads In Java


There are two types of threads in java. One is User Thread and another one is Daemon Thread. User threads
are high priority threads which always run in foreground. Where as Daemon threads are low priority threads
which always run in background. User threads are designed to do some specific task where as daemon threads
are used to perform some supporting tasks. In this post, we will discuss some of the differences between user
thread vs daemon thread and see how they differ from each other.
69
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

User Threads Daemon Threads


User threads are created by daemon threads are mostly created by
the application (user) to perform some the JVM to perform some background tasks
specific task. like garbage collection.

JVM waits for user threads to finish their JVM will not wait for daemon threads to
work. It will not exit until all user threads finish their work. It will exit as soon as all user
finish their work. threads finish their work.

Daemon threads are background threads.


They always run in background and act in a
User threads are foreground threads. supporting role to user threads.

Daemon threads are low priority threads.


User threads are high priority threads. They are designed to serve the user threads.

Daemon threads, in most of time, are created


User threads are created by the application. by the JVM.

User threads are mainly designed to do some Daemon threads are designed to support the
specific task. The application is very much user threads. The application is less
dependent on the user threads for it’s dependent on the daemon threads for it’s
smooth execution. smooth running.

JVM will not force the user threads to JVM will force the daemon threads to
terminate. It will wait for user threads to terminate if all user threads have finished
terminate themselves. their work.

70
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 THREAD POOLING
Pooling is usually implemented by loop i.e to check some condition repeatedly. Once condition is true
appropriate action is taken. This waste CPU time.
Java Thread pool represents a group of worker threads that are waiting for the job and reuse many
times.
In case of thread pool, a group of fixed size threads are created. A thread from the thread pool is pulled
out and assigned a job by the service provider. After completion of the job, thread is contained in the thread
pool again.
 Advantage of Java Thread Pool
Better performance It saves time because there is no need to create new thread.

 Real time usage


It is used in Servlet and JSP where container creates a thread pool to process the request.

 Example of Java Thread Pool


• EXAMPLE OF JAVA THREAD POOL USING EXECUTORSERVICE AND EXECUTORS.
• File: WorkerThread.java
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
class WorkerThread implements Runnable
{
private String message;
public WorkerThread(String s)
{
this.message=s;
}
public void run()
{
System.out.println(Thread.currentThread().getName()+" (Start) message = "+message);
processmessage();//call processmessage method that sleeps the thread for 2 seconds
System.out.println(Thread.currentThread().getName()+" (End)");//prints thread name
}
private void processmessage()
{
try
{
Thread.sleep(2000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}

71
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 File: JavaThreadPoolExample.java
public class TestThreadPool
{
public static void main(String[] args)
{
ExecutorService executor = Executors.newFixedThreadPool(5);//creating a pool of 5 threads
for (int i = 0; i < 10; i++)
{
Runnable worker = new WorkerThread("" + i);
executor.execute(worker);//calling execute method of ExecutorService
}
executor.shutdown();
while (!executor.isTerminated()) { }
System.out.println("Finished all threads");
}
}
Output:
pool-1-thread-1 (Start) message = 0
pool-1-thread-2 (Start) message = 1
pool-1-thread-3 (Start) message = 2
pool-1-thread-5 (Start) message = 4
pool-1-thread-4 (Start) message = 3
pool-1-thread-2 (End)
pool-1-thread-2 (Start) message = 5
pool-1-thread-1 (End)
pool-1-thread-1 (Start) message = 6
pool-1-thread-3 (End)
pool-1-thread-3 (Start) message = 7
pool-1-thread-4 (End)
pool-1-thread-4 (Start) message = 8
pool-1-thread-5 (End)
pool-1-thread-5 (Start) message = 9
pool-1-thread-2 (End)
pool-1-thread-1 (End)
pool-1-thread-4 (End)
pool-1-thread-3 (End)
pool-1-thread-5 (End)
Finished all threads

72
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 MULTITHREADING IN JAVA WITH EXAMPLES


The main purpose of multithreading is to provide simultaneous execution of two or more parts of a program
to maximum utilize the CPU time. A multithreaded program contains two or more parts that can run
concurrently. Each part of such a program called a thread. Each thread has a separate path of its execution. So
this way a single program can perform two or more tasks simultaneously.
Threads are lightweight processes; they share the same address space. In Multithreaded environment,
programs make maximum use of CPU so that the idle time can be kept to minimum.
Handling of multithreading in java is quite simple. We will learn that in this post.
There are several thread states, A thread can be in any one of the state at a particular point of time. It
can be running state. It can be ready to run state as soon as it gets CPU time. A running thread can be
suspended. A suspended thread can be resumed. A thread can be blocked when waiting for a resource. At any
time a thread can be terminated.
A program can be divided into a number of small processes. Each small process can be addressed as a
single thread (a lightweight process). Multithreaded programs contain two or more threads that can run
concurrently. This means that a single program can perform two or more tasks simultaneously. For example,
one thread is writing content on a file at the same time another thread is performing spelling check.
Java is a multi threaded programming language which means we can develop multi threaded program
using Java. A multi threaded program contains two or more parts that can run concurrently and each part can
handle different task at the same time making optimal use of the available resources specially when your
computer has multiple CPUs.
By definition multitasking is when multiple processes share common processing resources such as a
CPU. Multi threading extends the idea of multitasking into applications where you can subdivide specific
operations within a single application into individual threads. Each of the threads can run in parallel. The OS
divides processing time not only among different applications, but also among each thread within an
application.
Multi threading enables you to write in a way where multiple activities can proceed concurrently in the
same program.

 MAJOR JAVA MULTITHREADING CONCEPTS:


While doing Multithreading programming in Java, you would need to have the following concepts very
handy:
• In Java, the word thread means two different things.
1. An instance of Thread class.
2. or, A thread of execution.

An instance of Thread class is just an object, like any other object in java. But a thread of execution means an
individual "lightweight" process that has its own call stack. In java each thread has its own call stack.

73
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 A LOOK AT THE METHODS THAT HELPS IN MANAGING THE THREADS.


 getName(): It is used for Obtaining a thread’s name
 getPriority(): Obtain a thread’s priority
 isAlive(): Determine if a thread is still running
 join(): Wait for a thread to terminate
 run(): Entry point for the thread
 sleep(): suspend a thread for a period of time
 start(): start a thread by calling its run() method

 Method 1: Thread creation by implementing Runnable Interface


• One way of creating a thread is to create a class that implements the Runnable interface. We must
need to give the definition of run() method.
• This run method is the entry point for the thread and thread will be alive till run method finishes its
execution.
• Once the thread is created it will start running when start()method gets called. Basically start() method
calls run() method implicitly.
• A SIMPLE EXAMPLE
class MultithreadingDemo implements Runnable
{
public void run()
{
System.out.println("My thread is in running state.");
}
public static void main(String args[]) Output:
{ My thread is in running state.
MultithreadingDemo obj=new MultithreadingDemo();
Thread tobj =new Thread(obj);
tobj.start();
}
}

74
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 Example Program 2:
• Observe the output of this program and try to understand what is happening in this program.
If you have understood the usage of each thread method then you would not face any issue,
understanding this example.
class Count implements Runnable
{
Thread mythread ;
Count()
{
mythread = new Thread(this, "my runnable thread");
System.out.println("my thread created" + mythread);
mythread.start();
}
public void run()
{
Output:
try my thread createdThread[my runnable thread,5,main]
{ Main thread will be alive till the child thread is live
for (int i=0 ;i<10;i++) Printing the count 0
{ Printing the count 1
System.out.println("Printing the count " + i); Main thread will be alive till the child thread is live
Printing the count 2
Thread.sleep(1000); Main thread will be alive till the child thread is live
} Printing the count 3
} Printing the count 4
catch(InterruptedException e) Main thread will be alive till the child thread is live
{ Printing the count 5
Main thread will be alive till the child thread is live
System.out.println("my thread interrupted"); Printing the count 6
} Printing the count 7
System.out.println("mythread run is over" ); Main thread will be alive till the child thread is live
} Printing the count 8
} Main thread will be alive till the child thread is live
Printing the count 9
class RunnableExample mythread run is over
{ Main thread run is over
public static void main(String args[])
{
Count cnt = new Count();
try
{
while(cnt.mythread.isAlive())
{
System.out.println("Main thread will be alive till the child thread is live");
Thread.sleep(1500);
}
}
catch(InterruptedException e)
{
System.out.println("Main thread interrupted");
}
System.out.println("Main thread run is over" ); } }
75
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 Method 2: Thread creation by extending Thread class


• This is the second way of creating a thread. Here we need to create a new class that extends
the Thread class.
• The class should override the run() method which is the entry point for the new thread .
• Call start() method to start the execution of a thread.
 Example 1:
class MultithreadingDemo extends Thread
{
public void run()
{
System.out.println("My thread is in running state.");
}
public static void main(String args[])
{
MultithreadingDemo obj=new MultithreadingDemo();
obj.start();
}
}
Output:
My thread is in running state.
 Example 2:
class Count extends Thread
{
Count()
{
super("my extending thread");
System.out.println("my thread created" + this);
start();
}
public void run()
{
try
{
for (int i=0 ;i<10;i++)
{
System.out.println("Printing the count " + i);
Thread.sleep(1000);
}
}
catch(InterruptedException e)
{
System.out.println("my thread interrupted");
}
System.out.println("My thread run is over" );
}
}

76
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

class ExtendingExample
{
public static void main(String args[])
{
Count cnt = new Count();
try
{
while(cnt.isAlive())
{
System.out.println("Main thread will be alive till the child thread is live");
Thread.sleep(1500);
}
}
catch(InterruptedException e)
{
System.out.println("Main thread interrupted");
}
System.out.println("Main thread's run is over" );
}
}

 The main thread


• Even if you don't create any thread in the program, a thread called main thread is still created.
Although themain thread is automatically created, can control it by obtaining a reference to it by
callingcurrentThread() method.
• Two important things to know about main thread are,
• It is the thread from which other threads will be produced.
• main thread must be always the last thread to finish execution.
class MainThread
{
public static void main(String[] args)
{
Thread t=Thread.currentThread();
t.setName("MainThread");
System.out.println("Name of thread is "+t);
}
}
Output : Name of thread is Thread[MainThread,5,main]

77
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 DEADLOCK IN JAVA
Whenever there is multiple processes contending for exclusive access to multiple locks, there is the possibility
of deadlock. A set of processes or threads is said to be deadlocked when each is waiting for an action that only
one of the others can perform.
In Order to avoid deadlock, one should ensure that when you acquire multiple locks, you always
acquire the locks in the same order in all threads.
There are situations when programs become deadlocked when each thread is waiting on a resource
that cannot become available. The simplest form of deadlock is when two threads are each waiting on a
resource that is locked by the other thread. Since each thread is waiting for the other thread to relinquish a
lock, they both remain waiting forever in the Blocked-for-lock-acquisition state. The threads are said to be
deadlocked.
Thread t1 at tries to synchronize first on string s1 and then on string s2. The thread t2 does the opposite. It
synchronizes first on string s2 then on string s1.

 What Is Deadlock In Java?


Deadlock in java is a condition which occurs when two or more threads get blocked waiting for each other for
an infinite period of time to release the resources(Locks) they hold. Deadlock is the common problem in multi
threaded programming which can completely stops the execution of an application. So, extra care need to be
taken while writing the multi threaded programs so that deadlock never occurs.
So, deadlock in java is a part of multithreading. Deadlock can occur in a situation when a thread is waiting for
an object lock, that is acquired by another thread and second thread is waiting for an object lock that is
acquired by first thread. Since, both threads are waiting for each other to release the lock, the condition is
called deadlock.

78
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

NOTE:-Deadlock is a situation of complete Lock, when no thread can complete its execution because lack of
resources. In the above picture, Thread 1 is holding a resource R1, and need another resource R2 to finish
execution, but R2 is locked by Thread 2, which needs R3, which in turn is locked by Thread 3. Hence none of
them can finish and are stuck in a deadlock.
 Example of deadlock
class Pen{ }
class Paper{ }
public class Write
{
public static void main(String[] args)
{
final Pen pn =new Pen();
final Paper pr =new Paper();
Thread t1 = new Thread(){
public void run()
{
synchronized(pn)
{
System.out.println("Thread1 is holding Pen");
try
{
Thread.sleep(1000);
}
catch(InterruptedException e){}
synchronized(pr)
{
System.out.println("Requesting for Paper");
}
}
}
}

79
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

Thread t2 = new Thread()


{
public void run()
{
synchronized(pr)
{
System.out.println("Thread2 is holding Paper");
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{ }
synchronized(pn)
{
System.out.println("requesting for Pen");
}
}
}
}
t1.start();
t2.start();
}
}
Output
Thread1 is holding Pen
Thread2 is holding Paper

 Another 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()
{
synchronized (resource1)
{
System.out.println("Thread 1: locked resource 1");
try
{
Thread.sleep(100);
}
catch (Exception e) { }
80
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

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");
}
}
}
}
t1.start();
t2.start();
}
}
Output:
Thread 1: locked resource 1
Thread 2: locked resource 2

81
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 SIMPLE EXAMPLE OF DEADLOCK CONDITION.


class Shared
{
synchronized void methodOne(Shared s)
{
Thread t = Thread.currentThread();
System.out.println(t.getName()+"is executing methodOne...");
System.out.println(t.getName()+"is calling methodTwo...");
s.methodTwo(this);
System.out.println(t.getName()+"is finished executing methodOne...");
}
synchronized void methodTwo(Shared s)
{
Thread t = Thread.currentThread();
System.out.println(t.getName()+"is executing methodTwo...");
System.out.println(t.getName()+"is calling methodOne...");
s.methodOne(this);
System.out.println(t.getName()+"is finished executing methodTwo...");
}
}
public class DeadLockInJava
{
public static void main(String[] args)
{
final Shared s1 = new Shared();
final Shared s2 = new Shared();
Thread t1 = new Thread()
{
public void run()
{
s1.methodOne(s2);
}
}
Thread t2 = new Thread()
{
public void run()
{
s2.methodTwo(s1);
}
}
t1.start();
t2.start();
}
}

 EXPLANATION:-
82
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

• In the above multithreaded program, thread t1 and t2 are concurrent threads i.e they are executing
their task simultaneously. There are two Shared class objects, s1 and s2, which are shared by both the
threads. Shared class has two synchronized methods, methodOne() and methodTwo(). That means,
only one thread can execute these methods at a given time.
• First, thread t1 enters the methodOne() of s1 object by acquiring the object lock of s1. At the same
time, thread t2 also enters the methodTwo() of s2 object by acquiring the object lock
of s2. methodOne() of s1object, currently executing by thread t1, calls methodTwo() of s2 object from
it’s body. So, thead t1 tries to acquire the object lock of s2 object. But object lock of s2 object is already
acquired by thread t2. So, threadt1 waits for thread t2 to release the object lock of s2 object.
• At the same time, thread t2 is also executing methodTwo() of s2 object. methodTwo() of s2 object also
makes a call to methodOne() of s1 object. So, thread t2 tries to acquire the object lock of s1 object.
But, it is already acquired by thread t1. So, thread t2 also waits for thread t1 to release the object lock
of s1 object.
• Thus, both the threads wait for each other to release the object locks they own. They wait for infinite
period of time to get the object locks owned by opposite threads. This condition of threads waiting
forever is called Deadlock.

83
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 PROGRAM THAT ILLUSTRATES DEADLOCKS IN MULTITHREADING


APPLICATIONS
public class DeadLockExample
{
String o1 = "Lock ";
String o2 = "Step ";
Thread t1 = (new Thread("Printer1")
{
public void run()
{
while (true)
{
synchronized (o1)
{
synchronized (o2)
{
System.out.println(o1 + o2);
} } } } } )
Thread t2 = (new Thread("Printer2")
{
public void run()
{
while (true)
{
synchronized (o2)
{
synchronized (o1)
{
System.out.println(o2 + o1);
} } } } } )
public static void main(String[] args)
{
DeadLockExample dLock = new DeadLockExample();
dLock.t1.start();
dLock.t2.start();
}
}
• Note:
The following methods namely join, sleep and wait name the InterruptedException in its throws clause and
can have a timeout argument as a parameter. The following methods namely wait, notify andnotifyAll should
only be called by a thread that holds the lock of the instance on which the method is invoked. The Thread.start
method causes a new thread to get ready to run at the discretion of the thread scheduler. The Runnable
interface declares the run method. The Thread class implements the Runnable interface. Some
implementations of the Thread.yield method will not yield to a thread of lower priority. A program will
terminate only when all user threads stop running. A thread inherits its daemon status from the thread that
created it.

84
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 What if we call run() method directly without using start() method ?


• In above program if we directly call run() method, without using start() method,
public static void main( String args[] )
{
MyThread mt = new MyThread();
mt.run();
}
NOTE:-
Doing so, the thread won't be allocated a new call stack, and it will start running in the current call stack, that
is the call stack of the main thread. Hence Multithreading won't be there.

 How To Detect The Deadlocked Threads In Java


Deadlock is the condition which occurs when two or more threads wait for each other forever.
Programmatically, You can detect the threads which have entered into deadlock condition and also you can
retrieve the details about them. This can be
done using ThreadMXBean interface of java.lang.Managementpackage. You can go through the oracle
docs of ThreadMXBean interface here.
First, you have to get an instance of ThreadMXBean using getThreadMXBean() method
of ManagementFactory, like this.
ThreadMXBean bean = ManagementFactory.getThreadMXBean();
After getting an instance of ThreadMXBean, call findMonitorDeadlockedThreads() method on it. It returns
an array of type long containing ids of all currently deadlocked threads.
long ids[] = bean.findMonitorDeadlockedThreads();
After getting the ids of deadlocked threads, pass these ids to getThreadInfo() method of ThreadMXBean. It
will return an array of ThreadInfo objects, where one ThreadInfo object contains the details of one
deadlocked thread.
ThreadInfo threadInfo[] = bean.getThreadInfo(ids);
Iterate the ThreadInfo array to get the details of individual deadlocked thread.
for (ThreadInfo threadInfo1 : threadInfo)
{
System.out.println(threadInfo1.getThreadName()); //Prints the name of deadlocked thread
}
85
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 Here are the some methods of ThreadInfo class which are useful to retrieve the details
of deadlocked threads.
 getThreadId() —> Returns the ID of a deadlocked thread.
 getThreadName() —> Returns the name of a deadlocked thread.
 getBlockedTime() —> Returns the elapsed time in milli seconds that a thread is in deadlock
condition.
 getLockName() —> Returns string representation of an object for which thread has been
waiting.
 getLockOwnerId() —> Returns ID of a thread that currently owns the object lock.
 getLockOwnerName() —> Returns the name of a thread that currently owns the object lock.

86
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 Example that has been modified to get the details of deadlocked threads.
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
class Shared
{
synchronized void methodOne(Shared s)
{
Thread t = Thread.currentThread();
System.out.println(t.getName()+"is executing methodOne...");
try
{
Thread.sleep(2000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println(t.getName()+"is calling methodTwo...");
s.methodTwo(this);
System.out.println(t.getName()+"is finished executing methodOne...");
}
synchronized void methodTwo(Shared s)
{
Thread t = Thread.currentThread();
System.out.println(t.getName()+"is executing methodTwo...");
try
{
Thread.sleep(2000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println(t.getName()+"is calling methodOne...");
s.methodOne(this);
System.out.println(t.getName()+"is finished executing methodTwo...");
}
}
public class ThreadsInJava
{
public static void main(String[] args)
{
final Shared s1 = new Shared();
final Shared s2 = new Shared();
Thread t1 = new Thread()
{
public void run()
{
s1.methodOne(s2);
}
}

87
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

Thread t2 = new Thread()


{
public void run()
{
s2.methodTwo(s1);
}
}
t1.start();
t2.start();
try
{
Thread.sleep(5000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
ThreadMXBean bean = ManagementFactory.getThreadMXBean();
long ids[] = bean.findMonitorDeadlockedThreads();
if(ids != null)
{
ThreadInfo threadInfo[] = bean.getThreadInfo(ids);
for (ThreadInfo threadInfo1 : threadInfo)
{
System.out.println(threadInfo1.getThreadId()); //Prints the ID of deadlocked thread
System.out.println(threadInfo1.getThreadName()); //Prints the name of deadlocked thread
System.out.println(threadInfo1.getLockName()); /*Prints the string representation of an object for which thread has
entered into deadlock.*/
System.out.println(threadInfo1.getLockOwnerId()); //Prints the ID of thread which currently owns the object lock
System.out.println(threadInfo1.getLockOwnerName()); /*Prints name of the thread which currently owns the
object lock.*/
}
}
else
{
System.out.println("No Deadlocked Threads");
}
}
}

88
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

INTERTHREAD COMMUNICATION
Threads can communicate with each other using wait(), notify() and notifyAll() methods. These methods are
final methods of java.lang.Object class. That means every class in java will have these methods. All these
methods can only be called from within a synchronized method.

1) To understand synchronization java has a concept of monitor. Monitor can be thought of as a box which
can hold only one thread. Once a thread enters the monitor all the other threads have to wait until that thread
exits the monitor.
2) wait() tells the calling thread to give up the monitor and go to sleep until some other thread enters the
same monitor and calls notify().
3) notify() wakes up the first thread that called wait() on the same object.notifyAll() wakes up all the threads
that called wait() on the same object. The highest priority thread will run first.

 Inter-thread communication or Co-operation is all about allowing synchronized


threads to communicate with each other.
Cooperation (Inter-thread communication) is a mechanism in which a thread is paused running in its critical
section and another thread is allowed to enter (or lock) in the same critical section to be executed.It is
implemented by following methods ofObject class:
1. wait()
2. notify()
3. notifyAll()

1) wait() method
Causes current thread to release the lock and wait until either another thread invokes the notify() method or
the notifyAll() method for this object, or a specified amount of time has elapsed.
The current thread must own this object's monitor, so it must be called from the synchronized method only
otherwise it will throw exception.
Method Description
public final void wait()throws InterruptedException waits until object is notified.
public final void wait(long timeout)throws waits for the specified amount of time.
InterruptedException

2) notify() method
Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this object, one
of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation.
Syntax:public final void notify()

3) notifyAll() method
Wakes up all threads that are waiting on this object's monitor.
Syntax:public final void notifyAll()

89
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 Understanding the process of inter-thread communication

 The point to point explanation of the above diagram is as follows:


• Threads enter to acquire lock.
• Lock is acquired by on thread.
 Now thread goes to waiting state if you call wait() method on the object. Otherwise it releases the lock
and exits.
 If you call notify() or notifyAll() method, thread moves to the notified state (runnable state).
 Now thread is available to acquire lock.
 After completion of the task, thread releases the lock and exits the monitor state of the object.

 Why wait(), notify() and notifyAll() methods are defined in Object class not Thread
class?
 It is because they are related to lock and object has a lock.

 Difference between wait and sleep?

wait() sleep()
wait() method releases the lock sleep() method doesn't release the lock.
is the method of Object class is the method of Thread class
is the non-static method is the static method
is the non-static method is the static method
should be notified by notify() or notifyAll() after the specified amount of time, sleep is
methods completed.

90
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 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)
{
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);
} Output:
} going to withdraw...
start(); Less balance; waiting for deposit...
new Thread() going to deposit...
{ deposit completed...
public void run() withdraw completed
{
c.deposit(10000);
}
}
start();
}
}
91
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 public final void wait() throws InterruptedException


This method tells the currently executing thread to release the lock of this object and wait until some other
thread acquires the same lock and notify it using either notify() or notifyAll() methods. This method throws
InterruptedException if waiting thread is interrupted.
 public final void notify()
This method wakes up one thread randomly that called wait() method on this object.
 public final void notifyAll()
This method wakes up all the threads that called wait() method on this object. But, only one thread will
acquire lock of this object depending upon the priority.
 Important Note : These three methods must be called within synchronized method or block. Any
thread which calls these methods must have lock of that object.
 Below is an example for using wait() and notify() methods.
class Shared
{
synchronized void methodOne()
{
Thread t = Thread.currentThread();
System.out.println(t.getName()+" is relasing the lock and going to wait");
try
{
wait(); //releases the lock of this object and waits
}
catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println(t.getName()+" got the object lock back and can continue with it's execution");
}
synchronized void methodTwo()
{
Thread t = Thread.currentThread();
try
{
Thread.sleep(5000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
notify(); //wakes up one thread randomly which is waiting for lock of this object
System.out.println("A thread which is waiting for lock of this object is notified by "+t.getName());
}
}

92
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

public class ThreadsInJava


{
public static void main(String[] args)
{
final Shared s = new Shared();
Thread t1 = new Thread()
{
public void run()
{
s.methodOne(); //t1 calling methodOne() of 's' object
}
}
Thread t2 = new Thread()
{
public void run()
{
s.methodTwo(); //t2 calling methodTwo() of 's' object
}
}
t1.start();
t2.start();
}
}

Explanation:-
In this example, Thread t1 and t2 are sharing shared class object ‘s’. Thread t1 is calling methodOne() and
thread t2 is calling methodTwo() of ‘s’ object. Both the methods are synchronized. That means, for any thread
to enter these methods, they must acquire lock of ‘s’ object.

• First, thread t1 acquires the object lock and enters methodOne(). Thread t2 waits for thread t1 to
release the object lock. Thread t1 calls wait() method within methodOne(). As soon as, it calls wait()
method, It releases the lock of ‘s’ object and goes for wait. Thread t2 acquires this lock and enters
methodTwo(). After entering methodTwo(), thread t2 sleeps for 5 seconds and calls notify() method on
this object. It wakes up thread t1 which is waiting for this object lock. As soon as, thread t2 releases the
object lock after finishing it’s execution of methodTwo(), thread t1 acquires this lock and executes
remaining statements of methodOne(). In this manner, both threads t1 and t2 communicate with each
other and share the lock.

93
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 FOR MORE CLARIFICATION, SEE THE BELOW PICTURE.

 Java provide benefit of avoiding thread pooling using interthread communication.


The wait(), notify(),notifyAll() of Object class. These method are implemented as final in Object. All
three method can be called only from within a synchronized context.
• wait() tells calling thread to give up monitor and go to sleep until some other thread enters the same
monitor and call notify.
• notify() wakes up a thread that called wait() on same object.
• notifyAll() wakes up all the thread that called wait() on same object.

94
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 Some Things-To-Remember About wait(), notify() and notifyAll() :


 If a thread calls notify() method and more than one threads are waiting for the object lock, then only
one thread will be notified randomly.
 When a thread calls notifyAll() method on an object, it notifies all the threads which are waiting for this
object lock. But, only one thread will acquire this object lock depending upon priority.
 When you call sleep() method on a thread, thread goes to sleep with holding the object lock with it.
But, if you call wait() method, thread releases the object lock and goes for sleep. This is the main
difference between wait() and sleep() methods.
 wait(), notify() and notifyAll() are final methods of java.lang.Object class not java.lang.Thread class.
 wait(), notify() and notifyAll() – all these three methods throw IllegalMonitorStateException if the
calling thread does not owns the object lock.
 wait() method is overloaded in Object class. There are two more wait() methods available in Object
class. They are,
 public final void wait(long timeOut) —> This makes current thread to wait until any other thread calls
notify() or notifyAll() on this object or specified time(milli seconds) has elapsed.
 public final void wait(long timeOut, int nanos) —> This makes current thread to wait until any other
thread calls notify() or notifyAll() on this object or specified time(milli seconds + nano seconds) has
elapsed.

95
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 Thread Group In Java


• Java provides a convenient way to group multiple threads in a single object. In such way, we can
suspend, resume or interrupt group of threads by a single method call.
• Thread group in java is used to group similar threads into one unit. A thread group can also contain
other thread groups. Thread groups are constructed using java.lang.ThreadGroup class. The main use
of thread groups is that you can handle multiple threads simultaneously.
Note: Now suspend(), resume() and stop() methods are deprecated.
• Java thread group is implemented by java.lang.ThreadGroup class.
• Constructors of ThreadGroup class
 There are only two constructors of ThreadGroup class.
Constructor Description
ThreadGroup(String name) creates a thread group with given name.
ThreadGroup(ThreadGroup parent, String creates a thread group with given parent
name) group and name.

 Important methods of ThreadGroup class

METHOD DESCRIPTION
int activeCount() returns no. of threads running in current group.
int activeGroupCount() returns a no. of active group in this thread group.
void destroy() destroys this thread group and all its sub groups.
String getName() returns the name of this group.
ThreadGroup getParent() returns the parent of this group.
void interrupt() interrupts all threads of this group.
void list() prints information of this group to standard console.

 CODE TO GROUP MULTIPLE THREADS.


• ThreadGroup tg1 = new ThreadGroup("Group A");
• Thread t1 = new Thread(tg1,new MyRunnable(),"one");
• Thread t2 = new Thread(tg1,new MyRunnable(),"two");
• Thread t3 = new Thread(tg1,new MyRunnable(),"three");

 Now all 3 threads belong to one group. Here, tg1 is the thread group name, MyRunnable is the class
that implements Runnable interface and "one", "two" and "three" are the thread names.

96
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 INTERRUPT ALL THREADS BY A SINGLE LINE OF CODE ONLY.


• Thread.currentThread().getThreadGroup().interrupt();
public class ThreadGroupDemo implements Runnable
{
public void run()
{
System.out.println(Thread.currentThread().getName());
}
public static void main(String[] args)
{
ThreadGroupDemo runnable = new ThreadGroupDemo();
ThreadGroup tg1 = new ThreadGroup("Parent ThreadGroup");
Thread t1 = new Thread(tg1, runnable,"one");
t1.start();
Thread t2 = new Thread(tg1, runnable,"two");
t2.start();
Thread t3 = new Thread(tg1, runnable,"three");
t3.start();
System.out.println("Thread Group Name: "+tg1.getName());
tg1.list();
}
}
Output:
one
two
three
Thread Group Name: Parent ThreadGroup
java.lang.ThreadGroup[name=Parent ThreadGroup,maxpri=10]
Thread[one,5,Parent ThreadGroup]
Thread[two,5,Parent ThreadGroup]
Thread[three,5,Parent ThreadGroup]
 How To Add Threads To Thread Group :
While creating the threads itself, you can specify it’s group using constructor which takes ThreadGroup and
name of a thread as arguments. Below example shows how to add threads and child thread group to a parent
thread group.
public class ThreadGroupInJava
{
public static void main(String[] args)
{
//Creating Parent Thread Group
ThreadGroup parentGroup = new ThreadGroup("Parent Thread Group");
//Adding threads to ThreadGroup while creating threads itself
Thread t1 = new Thread(parentGroup, "Thread 1");
Thread t2 = new Thread(parentGroup, "Thread 2");
//Creating child thread group
ThreadGroup childGroup = new ThreadGroup(parentGroup, "Child Thread Group");
//Adding a thread to child thread group
Thread t3 = new Thread(childGroup, "Thread 3"); } }
97
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 Some Useful Methods Of ThreadGroup :


 getParent() Method :
• It returns the parent of the thread group in the form ClassName[name=name of the
parent, maxpri=Maximum priority].
public class ThreadGroupsInJava
{
public static void main(String[] args)
{
//Creating Parent Thread Group
ThreadGroup parentGroup = new ThreadGroup("Parent Thread Group ");
//Creating Child Thread Group
ThreadGroup childGroup = new ThreadGroup(parentGroup, "Child Thread Group");
//Printing parent of Child Thread Group
System.out.println(childGroup.getParent()); /*Output : java.lang.ThreadGroup[name=Parent Thread Group ,
maxpri=10]*/
}
}
 setDaemon() And isDaemon() Methods :
• setDaemon() method is used to set the daemon property of a thread group. isDaemon() is used to
check whether a thread group is daemon or not.
public class ThreadGroupsInJava
{
public static void main(String[] args)
{
//Creating Thread Group
ThreadGroup threadGroup = new ThreadGroup("Thread Group ");
//Setting the daemon property of thread group
threadGroup.setDaemon(true);
//Checking the daemon property of thread group
System.out.println(threadGroup.isDaemon()); //Output : true
}
}
 setMaxPriority() And getMaxPriority() Methods :
• setMaxPriority() is used to set the maximum priority of a thread group. getMaxPriority() method is
used to retrieve the maximum priority of a thread group.
public class ThreadGroupsInJava
{
public static void main(String[] args)
{
//Creating Thread Group
ThreadGroup threadGroup = new ThreadGroup("Parent Thread Group ");
//Setting the maximum priority of thread group
threadGroup.setMaxPriority(8);
//getting the maximum priority of thread group
System.out.println(threadGroup.getMaxPriority()); //Output : 8
} }

98
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 activeCount() and activeGroupCount() Methods


• activeCount() returns the number of active threads in a specified group and it’s
subgroups.activeGroupCount() returns the numbers of active thread groups in a specified group and
it’s subgroups.
public class ThreadGroupsInJava
{
public static void main(String[] args)
{
//Creating parent Thread Group
ThreadGroup parentGroup = new ThreadGroup("Parent Thread Group ");
Thread t1 = new Thread(parentGroup, "Thread 1")
{
public void run()
{
try
{
Thread.sleep(5000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
t1.start();
Thread t2 = new Thread(parentGroup, "Thread 2")
{
public void run()
{
try
{
Thread.sleep(5000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
t2.start();
//Creating Child Thread Group
ThreadGroup childGroup = new ThreadGroup(parentGroup, "Child Group");

99
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

Thread t3 = new Thread(childGroup, "Thread 3")


{
public void run()
{
try
{
Thread.sleep(5000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
t3.start();
//Checking Active thread count
System.out.println(parentGroup.activeCount()); //Output : 3
//Checking Active thread group count
System.out.println(parentGroup.activeGroupCount()); //Output : 1
}
}
 interrupt() Method :
• This method is used to interrupt all threads in a group.
public class ThreadsInJava
{
public static void main(String[] args)
{
//Creating Thread Group
ThreadGroup parentGroup = new ThreadGroup("Parent Group ");
Thread t1 = new Thread(parentGroup, "Thread 1")
{
public void run()
{
try
{
Thread.sleep(5000);
}
catch (InterruptedException e)
{
System.out.println("Thread interrupted");
}
}
}
t1.start();

100
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

Thread t2 = new Thread(parentGroup, "Thread 2")


{
public void run()
{
try
{
Thread.sleep(5000);
}
catch (InterruptedException e)
{
System.out.println("Thread interrupted");
}
}
}
t2.start();
ThreadGroup childGroup = new ThreadGroup(parentGroup, "Child Group");
Thread t3 = new Thread(childGroup, "Thread 3")
{
public void run()
{
try
{
Thread.sleep(5000);
}
catch (InterruptedException e)
{
System.out.println("Thread interrupted");
}
}
}
t3.start();
//Interrupting whole group
parentGroup.interrupt();
}
}
 destroy() Method :
• This method is used to destroy the whole thread group and it’s subgroups. Before calling this
method, thread group must be empty i.e all threads in a group must be exited. Otherwise this
method will throw IllegalThreadStateException.
public class ThreadGroupsInJava
{
public static void main(String[] args)
{
//Creating Thread Group
ThreadGroup parentGroup = new ThreadGroup("Parent Group ");
Thread t1 = new Thread(parentGroup, "Thread 1");
t1.start();
Thread t2 = new Thread(parentGroup, "Thread 2");
101
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

t2.start();
ThreadGroup childGroup = new ThreadGroup(parentGroup, "Child Group");
Thread t3 = new Thread(childGroup, "Thread 3");
t3.start();
try
{
Thread.sleep(2000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
//Destroying the whole group
parentGroup.destroy();
}
}
 enumerate() Method :
There exist four versions of enumerate() method in ThreadGroup class. They are,
1. public int enumerate(Thread[] list) —> It copies all active threads of a group into specified array of
threads.
2. public int enumerate(Thread[] list, boolean recurse) —> It copies all active threads of a group into
specified array of threads. If recurse is true, subgroups are also enumerated.
3. public int enumerate(ThreadGroup[] list) —> It copies all active subgroups of a thread group into
specified array of ThreadGroup.
4. public int enumerate(ThreadGroup[] list, boolean recurse) —> It copies all active subgroups of a
thread group into specified array of ThreadGroup. If recurse is true, subgroups of subgroups are also
enumerated.
public class ThreadsInJava
{
public static void main(String[] args)
{
//Creating Thread Group
ThreadGroup parentGroup = new ThreadGroup("Parent Group ");
Thread t1 = new Thread(parentGroup, "Thread 1")
{
public void run()
{
try
{
Thread.sleep(5000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
} }
t1.start();
Thread t2 = new Thread(parentGroup, "Thread 2")
102
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

{
public void run()
{
try
{
Thread.sleep(5000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
t2.start();
ThreadGroup childGroup = new ThreadGroup(parentGroup, "Child Group");
Thread t3 = new Thread(childGroup, "Thread 3")
{
public void run()
{
try
{
Thread.sleep(5000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
t3.start();
//Enumerating all active threads
Thread[] threads = new Thread[parentGroup.activeCount()];
int No_Of_Active_Threads = parentGroup.enumerate(threads);
System.out.println(No_Of_Active_Threads);
for (Thread thread : threads)
{
System.out.println(thread.getName());
}
}
}

 SOME IMPORTANT POINTS ON THREAD:-


103
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 If user starts a thread that is already started, get java.lang.IllegalThreadStateException


at run time. There will be no compilation errors.
public class ThreadsInJava
{
public static void main(String[] args)
{
Thread t = new Thread();
t.start();
t.start(); //This statement will throw java.lang.IllegalThreadStateException
}
}
 Exception is thread wise not execution wise. i.e exception effects the thread in which
it occurs. Other threads will execute normally. In the below example, exception occurs
in thread t1. only this thread will be terminated abruptly. Thread t2 will continue to
execute it’s task.
public class ThreadsInJava
{
public static void main(String[] args)
{
Thread t1 = new Thread()
{
public void run()
{
String s = null;
System.out.println(s.length()); //This statement will throw NullPointerException
System.out.println("This statement will not be executed");
}
}
Thread t2 = new Thread()
{
public void run()
{
for(int i = 0; i <= 1000; i++)
{
System.out.println(i);
}
}
}
t1.start();
t2.start();
}
}

 As all know that start() method internally calls run() method. What happens when you
call run() method directly?. When call run() method of a thread directly, calling thread
will execute the task defined in the run() method. For example, in the below

104
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

program main thread is calling run() method of thread t. In this case, main thread will
execute run() method not thread t.
public class ThreadsInJava
{
public static void main(String[] args)
{
Thread t = new Thread()
{
public void run()
{
System.out.println(Thread.currentThread().getName()); //Output : main
}
}
t.run();
}
}
 Which one is better way to implement threads in java. Is it using Thread class or using
Runnable interface?.
 It is the most confusing question for a java developer, of opinion that when multiple threads
need to execute same task, then use Runnable interface. If multiple threads need to execute
different tasks, then go for Thread class.
 Setting the priority to a thread is not effective as we thought. Setting Priority of a thread is just an
advice to OS not an instruction. It is up to OS to consider this advice.
 Every thread in java is a member of a thread group. When a java application first
starts up, Java runtime system creates a thread group called main. main thread is also
member of this group.
public class ThreadsInJava
{
public static void main(String[] args)
{
Thread t = Thread.currentThread();
System.out.println(t.getThreadGroup());
//Output : java.lang.ThreadGroup[name=main,maxpri=10]
}
}

 A thread is a permanent member of a thread group to which it joins during creation,


can’t move a thread to a new group after creating it.

105
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 SHUTDOWN HOOK
The shutdown hook can be used to perform cleanup resource or save the state when JVM shuts down
normally or abruptly. Performing clean resource means closing log file, sending some alerts or something else.
So if you want to execute some code before JVM shuts down, use shutdown hook.
 When does the JVM shut down?
• The JVM shuts down when:
 user presses ctrl+c on the command prompt
 System.exit(int) method is invoked
 user logoff
 user shutdown etc.
 The addShutdownHook(Runnable r) method
The addShutdownHook() method of Runtime class is used to register the thread with the Virtual Machine.
Syntax: public void addShutdownHook(Runnable r){ }
The object of Runtime class can be obtained by calling the static factory method getRuntime().
For example:
Runtime r = Runtime.getRuntime();

 Factory method
• The method that returns the instance of a class is known as factory method.
 Simple example of Shutdown Hook
class MyThread extends Thread
{
public void run()
{
System.out.println("shut down hook task completed..");
}
}
public class TestShutdown1
{
public static void main(String[] args)throws Exception
{
Runtime r=Runtime.getRuntime();
r.addShutdownHook(new MyThread());
System.out.println("Now main sleeping... press ctrl+c to exit");
try
{
Thread.sleep(3000);
}
catch (Exception e) { }
Note: The shutdown sequence can be
} stopped by invoking the halt(int) method of
} Runtime class.
Output:
Now main sleeping... press ctrl+c to exit
shut down hook task completed..
106
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 Same example of Shutdown Hook by annonymous class:


public class TestShutdown2
{
public static void main(String[] args)throws Exception
{
Runtime r=Runtime.getRuntime();
r.addShutdownHook(new Runnable()
{
public void run()
{
System.out.println("shut down hook task completed..");
}
}
)
System.out.println("Now main sleeping... press ctrl+c to exit");
try
{
Thread.sleep(3000);
}
catch (Exception e) { }
}
}
Output:
Now main sleeping... press ctrl+c to exit
shut down hook task completed..
How to perform single task by multiple threads?
If have to perform single task by many threads, have only one run() method.For example:
• Program of performing single task by multiple threads
class TestMultitasking1 extends Thread
{
public void run()
{
System.out.println("task one"); Output:
} task one
public static void main(String args[]) task one
{ task one
TestMultitasking1 t1=new TestMultitasking1();
TestMultitasking1 t2=new TestMultitasking1();
TestMultitasking1 t3=new TestMultitasking1();
t1.start();
t2.start();
t3.start();
}
}

107
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 Program of performing single task by multiple threads


class TestMultitasking2 implements Runnable
{
public void run()
{
System.out.println("task one");
}
public static void main(String args[])
{
Thread t1 =new Thread(new TestMultitasking2());//passing annonymous object of TestMultitasking2 class
Thread t2 =new Thread(new TestMultitasking2());
t1.start();
t2.start();
}
}
Output:
task one
task one
• Note: Each thread run in a separate callstack.

108
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 How to perform multiple tasks by multiple threads (multitasking in multithreading)?


• If have to perform multiple tasks by multiple threads,have multiple run() methods.
 For example:
 Program of performing two tasks by two threads
class Simple1 extends Thread
{
public void run()
{
System.out.println("task one");
}
}
class Simple2 extends Thread
{
public void run()
{
System.out.println("task two");
}
}
class TestMultitasking3
{
public static void main(String args[])
{
Simple1 t1=new Simple1();
Simple2 t2=new Simple2();
t1.start();
t2.start();
}
}
Output:
task one
task two
 Same example as above by annonymous class that extends Thread class:
 Program of performing two tasks by two threads
class TestMultitasking4 Thread t2=new Thread()
{ {
public static void main(String args[]) public void run()
{ {
Thread t1=new Thread() System.out.println("task two");
{ }
public void run() }
{ t1.start();
System.out.println("task one"); t2.start();
} }
} }
Output:
task one
task two

109
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 Example by annonymous class that implements Runnable interface:


 Program of performing two tasks by two threads
class TestMultitasking5
{
public static void main(String args[])
{
Runnable r1=new Runnable()
{
public void run()
{
System.out.println("task one");
}
}
Runnable r2=new Runnable()
{
public void run()
{
System.out.println("task two");
}
}
Thread t1=new Thread(r1);
Thread t2=new Thread(r2);
t1.start();
t2.start();
}
}
Output:
task one
task two

110
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 REENTRANT MONITOR IN JAVA


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
 The java reentrant monitor by the example given below:
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");
}
}
EXPLAIN:-In this class, m and n are the synchronized methods. The m() method internally calls the n() method
and call the m() method on a thread. In the class given below, and creating thread using annonymous class.
public class ReentrantExample
{
public static void main(String args[])
{
final ReentrantExample re=new ReentrantExample();
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

111
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 How To Stop A Thread In Java?


How do you stop a thread in java? now-a-days, this has been the popular question in the java interviews.
Because, stop() method has been deprecated for some safety reasons. As stop() method has been deprecated,
interviewer will be interested in what logic you will be using to stop a thread. There are two ways through
which you can stop a thread in java. One is using boolean variable and second one is usinginterrupt() method.
 How To Stop A Thread In Java Using A boolean Variable?
In this method, we declare one boolean variable called flag in a thread. Initially we set this flag as true. Keep
the task to be performed in while loop inside the run() method by passing this flag. This will make thread
continue to run until flag becomes false. We have defined stopRunning() method. This method will set
the flagas false and stops the thread. Whenever you want to stop the thread, just call this method. Also notice
that we have declared flag as volatile. This will make thread to read its value from the main memory, thus
making sure that thread always gets its updated value.
class MyThread extends Thread
{
//Initially setting the flag as true
private volatile boolean flag = true; Output :
//This method will set flag as false I am running….
public void stopRunning() I am running….
{ I am running….
flag = false; I am running….
} I am running….
public void run() I am running….
{ I am running….
//Keep the task in while loop I am running….
//This will make thread continue to run until flag becomes false I am running….
while (flag) I am running….
{ I am running….
System.out.println("I am running...."); I am running….
} I am running….
System.out.println("Stopped Running...."); I am running….
} } I am running….
public class MainClass I am running….
{ I am running….
public static void main(String[] args) I am running….
{ I am running….
MyThread thread = new MyThread(); I am running….
thread.start(); Stopped Running….
try
{
Thread.sleep(100);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
//call stopRunning() method whenever you want to stop a thread
thread.stopRunning();
} }
112
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 How To Stop A Thread In Java Using interrupt() Method?


In this method, we use interrupt() method to stop a thread. Whenever you call interrupt() method on a thread,
it sets the interrupted status of a thread. This status can be obtained by interrupted() method. This status is
used in a while loop to stop a thread.
class MyThread extends Thread
{
public void run()
{
while (!Thread.interrupted())
{ Output :
System.out.println("I am running....");
I am running….
}
I am running….
System.out.println("Stopped Running.....");
I am running….
}
I am running….
}
I am running….
public class MainClass
I am running….
{
I am running….
public static void main(String[] args)
I am running….
{
I am running….
MyThread thread = new MyThread();
I am running….
thread.start();
I am running….
try
I am running….
{
I am running….
Thread.sleep(100);
I am running….
}
I am running….
catch (InterruptedException e)
I am running….
{
I am running….
e.printStackTrace();
I am running….
}
I am running….
//interrupting the thread
I am running….
thread.interrupt();
I am running….
}
I am running….
}
I am running….
I am running….
I am running….
I am running….
Stopped Running…..

113
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 SYNCHRONIZATION IN JAVA
 Multithreading introduces asynchronous behavior to the programs. If a thread is writing some data
another thread may be reading the same data at that time. This may bring inconsistency.
 When two or more threads need access to a shared resource there should be some way that the
resource will be used only by one resource at a time. The process to achieve this is called
synchronization.
 To implement the synchronous behavior java has synchronous method. Once a thread is inside a
synchronized method, no other thread can call any other synchronized method on the same object. All
the other threads then wait until the first thread come out of the synchronized block.
 When want to synchronize access to objects of a class which was not designed for the multithreaded
access and the code of the method which needs to be accessed synchronously is not available with us,
in this case we cannot add the synchronized to the appropriate methods. In java we have the solution
for this, put the calls to the methods (which needs to be synchronized) defined by this class inside a
synchronized block in following manner.
Synchronized(object)
{
// statement to be synchronized
}
 Synchronize: It works with Lock. Lock is of two type.
1. Static lock
2. Non static lock
Note: There is only one lock per object. Once a thread got the lock of an object no other
thread can enter the synchronise block/method of given object.
 Only methods/block can be synchronised not variable or class.
 A class can have both synchronised / non synchronised method.
 Thread can access non synchronised block even if one Thread got the lock of give object.
 If a thread goes to sleep, it holds any locks it has. A thread can have Lock of different object at the
same time.
 Syntax :
class SyncTest
{
public void doStuff()
{
System.out.println("not synchronized");
synchronized(this)
{
System.out.println("synchroni
zed");
}
}
}

114
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 Synchronised Static method :


There is only one copy of the static data, so you only need one lock per class to synchronize static methods.
There is such a lock; every class loaded in Java has a corresponding instance of java.lang.Class representing
that class. It’s that java.lang.Class instance whose lock is used to protect the static methods of the class.
Syntax:
public static synchronized int getCount()
{
return count;
}
NOTE:- MyClass.class thing is called a class literal. It tells the compiler (who tells the JVM): go and find me the
instance of Class that represents the class called MyClass. Threads calling non-static synchronized methods in
the same class will only block each other if they’re invoked using the same instance. As there is only one lock
per instance. Threads calling static synchronized methods in the same class will always block each other— As
there is only one lock per class.
 IMPORTANT POINTS TO BR REMEMBER TO Synchronised
 Thread can be created by extending Thread Class and overriding the run() method.
 Thread can also be created by Implementing Runnable interface and then calling Thread constructor
that takes Runnable argument.
 start() method can be called on Thread Object only once.
 Once start() method is called on Thread Object it becomes thread of execution. Before start() method
called it is said to be in new state and is not considered alive.
 There is no guarantee of order in which Thread will get executed after getting started.
 We can influence the order in which Thread get executed by setting its(Thread) priority(1-10).
 A running thread may enter blocked/waiting state by wait(), sleep or join() call.
 A running thread may enter blocked/waiting state because it can’t acquire the lock of a synchronized
block of code.
 A dead thread can not be started again.
 Synchronized blocks should be short — as short as possible while still protecting the integrity of related
data operations.
 Don’t block. Don’t ever call a method that might block, such as InputStream.read(), inside a
synchronized block or method.
 Don’t invoke methods on other objects while holding a lock. This may sound extreme, but it eliminates
the most common source of deadlock.
 isAlive() and join() methods
 isAlive() method is used to determine if a thread is still alive. It is the best way to determine if a thread
has been started but has not yet completed its run() method. final boolean isAlive();
 The nonstatic join() method of class Thread lets one thread “join onto the end” of another thread. This
method waits until the thread on which it is called terminates. final void join();
 Blocking Threads
When reading from a stream, if input is not available, the thread will block
 Thread is suspended (“blocked”) until I/O is available
 Allows other threads to automatically activate
 When I/O available, thread wakes back up again
 Becomes “runnable” i.e. gets into ready state

115
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 Grouping of threads
Thread groups provide a mechanism for collecting multiple threads into a single object and manipulating those
threads all at once, rather than individually.
To put a new thread in a thread group the group must be explicitly specified when the thread is created
 public Thread(ThreadGroup group, Runnable runnable)
 public Thread(ThreadGroup group, String name)
 public Thread(ThreadGroup group, Runnable runnable, String name)
 A thread can not be moved to a new group after the thread has been created.
 When a Java application first starts up, the Java runtime system creates a ThreadGroup named main.
 Java thread groups are implemented by the java.lang.ThreadGroup class.

 Synchronization
 At times when more than one thread try to access a shared resource, we need to ensure that resource
will be used by only one thread at a time. The process by which this is achieved is
called synchronization. The synchronization keyword in java creates a block of code referred to as
critical section.
 Every Java object with a critical section of code gets a lock associated with the object. To enter critical
section a thread need to obtain the corresponding object's lock.
 General Syntax :
synchronized (object)
{
//statement to be synchronized
}
 Why we use Syncronization ?
 If we do not use syncronization, and let two or more threads access a shared resource at the same
time, it will lead to distorted results.
 Consider an example, Suppose we have two different threads T1 and T2, T1 starts execution and save
certain values in a file temporary.txt which will be used to calculate some result when T1 returns.
Meanwhile, T2 starts and before T1 returns, T2 change the values saved by T1 in the file temporary.txt
(temporary.txt is the shared resource). Now obviously T1 will return wrong result.
 To prevent such problems, synchronization was introduced. With synchronization in above case, once
T1 starts using temporary.txt file, this file will be locked(LOCK mode), and no other thread will be able
to access or modify it until T1 returns.
SO,
 The synchronization is mainly used to
 To prevent thread interference.
 To prevent consistency problem.

116
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 Using Synchronized Methods


Using Synchronized methods is a way to accomplish synchronization. But lets first see what happens when we
do not use synchronization in our program.
 Example with no Synchronization
class First
{
public void display(String msg)
{
System.out.print ("["+msg);
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
System.out.println ("]");
}
public class Syncro
}
{
class Second extends Thread
public static void main (String[] args)
{
{
String msg;
First fnew = new First();
First fobj;
Second ss = new second(fnew, "welcome");
Second (First fp,String str)
Second ss1= new second (fnew,"new");
{
Second ss2 = new second(fnew, "programmer");
fobj = fp;
}
msg = str;
}
start();
}
public void run()
Output :
{
[welcome [ new [ programmer]
fobj.display(msg);
]
}
]
}

EXPLANATION-
 In the above program, object fnew of class First is shared by all the three running threads(ss, ss1 and
ss2) to call the shared method(void display). Hence the result is unsynchronized and such situation is
called Race condition.
 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.

117
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 Types of Synchronization
There are two types of synchronization
1. Process Synchronization
2. Thread Synchronization
 Thread Synchronization
There are two types of thread synchronization
1. mutual exclusive
2. inter-thread communication.
1. Mutual Exclusive
 Synchronized method.
 Synchronized block.
 static synchronization.
 Cooperation (Inter-thread communication in java)
So, 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
 Concept of Lock in Java
 Synchronization is built around an internal entity known as the lock or monitor. Every object has an
lock associated with it. By convention, a thread that needs consistent access to an object's fields has to
acquire the object's lock before accessing them, and then release the lock when it's done with them.
 From Java 5 the package java.util.concurrent.locks contains several lock implementations.
 Understanding the problem without Synchronization
In this example, there is no synchronization, so output is inconsistent.
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);
}
}
}
}

118
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

class MyThread1 extends Thread


{
Table t;
MyThread1(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(5);
}
Output:
}
5
class MyThread2 extends Thread
100
{
10
Table t;
200
MyThread2(Table t)
15
{
300
this.t=t;
20
}
400
public void run()
25
{
500
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();
}
}

119
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 THREAD SYNCHRONIZATION
 With respect to multithreading, Synchronization is a process of controlling the access of shared
resources by the multiple threads in such a manner that only one thread can access a particular
resource at a time.
 In non synchronized multithreaded application, it is possible for one thread to modify a shared object
whileanother thread is in the process of using or updating the object’s value. Synchronization prevents
such typeof data corruption which may otherwise lead to dirty reads and significant errors.
 Generally critical sections of the code are usually marked with synchronized keyword.
 Examples of using Thread Synchronization is in “The Producer/Consumer Model”.
Locks are used to synchronize access to a shared resource. A lock can be associated with a shared resource.
Threads gain access to a shared resource by first acquiring the lock associated with the object/block of code.
At any given time, at most only one thread can hold the lock and thereby have access to the shared resource.
A lock thus implements mutual exclusion.
 The object lock mechanism enforces the following rules of synchronization:
 A thread must acquire the object lock associated with a shared resource, before it can enter the shared
resource. The runtime system ensures that no other thread can enter a shared resource if another
thread
already holds the object lock associated with the shared resource. If a thread cannot immediately
acquire
the object lock, it is blocked, that is, it must wait for the lock to become available.
 When a thread exits a shared resource, the runtime system ensures that the object lock is also
relinquished.
If another thread is waiting for this object lock, it can proceed to acquire the lock in order to gain
access
to the shared resource.
 Classes also have a class-specific lock that is analogous to the object lock. Such a lock is actually a
lock on the java.lang.Class object associated with the class. Given a class A, the reference A.class
denotes this unique Class object. The class lock can be used in much the same way as an object lock to
implement mutual exclusion.

There can be 2 ways through which synchronized can be implemented in Java:


 synchronized methods
 synchronized blocks

120
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 SYNCHRONIZED METHODS
 PROERTIES:-
1. Synchronized methods are methods that are used to control access to an object.
2. A thread only executes a synchronized method after it has acquired the lock for the method’s object or
class. .If the lock is already held by another thread, the calling thread waits.
3. A thread relinquishes the lock simply by returning from the synchronized method, allowing the next
thread waiting for this lock to proceed.
4. Synchronized methods are useful in situations where methods can manipulate the state of an object in
ways that can corrupt the state if executed concurrently. This is called a race condition. It occurs when
two or more threads simultaneously update the same value, and as a consequence, leave the value in
an undefined or inconsistent state. While a thread is inside a synchronized method of an object, all
other threads that wish to execute this synchronized method or any other synchronized method of the
object will have to wait until it gets the lock. This restriction does not apply to the thread that already
has the lock and is executing a synchronized method of the object. Such a method can invoke other
synchronized methods of the object without being blocked.
5. The non-synchronized methods of the object can of course be called at any time by any thread.
6. If you declare any method as synchronized, it is known as synchronized method.
7. Synchronized method is used to lock an object for any shared resource.
8. When a thread invokes a synchronized method, it automatically acquires the lock for that object and
releases it when the thread completes its task.
9. Any method is specified with the keyword synchronized is only executed by one thread at a time. If
any thread wants to implement the synchronized method, firstly it has to obtain the objects lock. If the
lock is already held by another thread, then calling thread has to wait.
10. Synchronized methods are useful in those situations where methods are executed concurrently, so that
these can be intercommunicate control the state of an object in ways that can corrupt the state if .
11. Stack implementations usually define the two operations push and pop of elements as synchronized,
that‘s why pushing and popping are mutually exclusive process.

 For Example - if several threads were sharing a stack, if one thread is popping the
element on the stack then another thread would not be able to pushing the element
on the stack.

The following program demonstrates the synchronized method:


class Demo extends Thread
{
static String msg[]={"This", "is", "a", "synchronized", "variable"};
Share(String threadname)
{
super(threadname);
}
public void run()
{
display(getName());
}

121
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

public synchronized void display(String threadN)


{
for(int i=0;i<=4;i++)
{
System.out.println(threadN+msg[i]);
}
try
{
this.sleep(1000);
}
catch(Exception e){ }
}
}
public class SynThread1
{
public static void main(String[] args)
{
Share t1=new Share("Thread One: ");
t1.start();
Share t2=new Share("Thread Two: ");
t2.start();
}
}
Output of the program is:
Thread One: variable
Thread Two: This
Thread Two: is
Thread two: a
Thread Two: synchronized Thread Two: variable C:\nisha>javac SynThread.java C:\nisha>java SynThread
Thread One: This
Thread One: is
Thread One: a
Thread One: synchronized Thread One: variable Thread Two: This
Thread Two: is
Thread two: a
Thread Two: synchronized
Thread Two: variable

122
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 Below is an example shows how synchronized methods and object locks are used to
coordinate access to a common object by multiple threads. If the ‘synchronized’
keyword is removed, the message is displayed in random fashion.
public class SyncMethodsExample extends Thread
{
static String[] msg = { "Beginner", "java", "tutorial,", ".,", "com","is", "the", "best" };
public SyncMethodsExample(String id)
{
super(id);
}
public static void main(String[] args)
{
SyncMethodsExample thread1 = new SyncMethodsExample("thread1: ");
SyncMethodsExample thread2 = new SyncMethodsExample("thread2: ");
thread1.start();
thread2.start();
boolean t1IsAlive = true;
boolean t2IsAlive = true;
do
{
if (t1IsAlive &amp;&amp; !thread1.isAlive())
{
t1IsAlive = false;
System.out.println("t1 is dead.");
}
if (t2IsAlive &amp;&amp; !thread2.isAlive())
{
t2IsAlive = false;
System.out.println("t2 is dead.");
}
}
while (t1IsAlive || t2IsAlive);
}
void randomWait()
{
try
{
Thread.currentThread().sleep((long) (3000 * Math.random()));
}
catch (InterruptedException e)
{
System.out.println("Interrupted!");
}
}
public synchronized void run()
{
SynchronizedOutput.displayList(getName(), msg);
}}
123
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

class SynchronizedOutput
{
// if the 'synchronized' keyword is removed, the message
// is displayed in random fashion
public static synchronized void displayList(String name, String list[])
{
for (int i = 0; i &lt; list.length; i++)
{
SyncMethodsExample t = (SyncMethodsExample) Thread.currentThread();
t.randomWait();
System.out.println(name + list[i]);
}
}
}
Output
thread1: Beginner
thread1: java
thread1: tutorial,
thread1: .,
thread1: com
thread1: is
thread1: the
thread1: best
t1 is dead.
thread2: Beginner
thread2: java
thread2: tutorial,
thread2: .,
thread2: com
thread2: is
thread2: the
thread2: best
t2 is dead.

124
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 Synchronized Methods Thread Program Example Class Locks


//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)
{
this.t=t;
}
public void run()
{
t.printTable(5);
} }
class MyThread2 extends Thread
{
Table t;
MyThread2(Table t)
{ Output:
this.t=t; 5
} 10
public void run() 15
{ 20
t.printTable(100); 25
} } 100
public class TestSynchronization2 200
{ 300
public static void main(String args[]) 400
{ 500
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start(); } }

125
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 Example of synchronized method by using annonymous class


 In this program, we have created the two threads by annonymous class, so less coding is required.
//Program of synchronized method by using annonymous class
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);
} } } }
public class TestSynchronization3
{
public static void main(String args[])
{
final Table obj = new Table();//only one object
Thread t1=new Thread()
{
public void run()
{ Output:
obj.printTable(5); 5
} 10
} 15
Thread t2=new Thread() 20
{ 25
public void run() 100
{ 200
obj.printTable(100); 300
} 400
} 500
t1.start();
t2.start();
}
}

126
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 SYNCHRONIZED BLOCKS
 Static methods synchronize on the class lock. Acquiring and relinquishing a class lock by a thread in
order to execute a static synchronized method, proceeds analogous to that of an object lock for a
synchronized instance method.
 A thread acquires the class lock before it can proceed with the execution of any static synchronized
method in the class, blocking other threads wishing to execute any such methods in the same class.
This, of course, does not apply to static, non-synchronized methods, which can be invoked at any time.
 Synchronization of static methods in a class is independent from the synchronization of instance
methods on objects of the class.
 A subclass decides whether the new definition of an inherited synchronized method will remain
synchronized in the subclass.
 The synchronized block allows execution of arbitrary code to be synchronized on the lock of an
arbitrary object.

 The general form of the synchronized block is as follows:


synchronized (<object reference expression>)
{
<code block>
}
NOTE:-
1. A compile-time error occurs if the expression produces a value of any primitive type. If execution of the
block completes normally, then the lock is released. If execution of the block completes abruptly, then
the lock is released.
2. A thread can hold more than one lock at a time. Synchronized statements can be nested. Synchronized
statements with identical expressions can be nested. The expression must evaluate to a non-null
reference value, otherwise, a NullPointerException is thrown.
3. The code block is usually related to the object on which the synchronization is being done.

 The case with synchronized methods, where the execution of the method is
synchronized on the lock of the current object:
public Object method()
{
synchronized (this) // Synchronized block on current object
{
// method block
}
}

127
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 POINTS TO REMEMBER FOR SYNCHRONIZED BLOCK


 Once a thread has entered the code block after acquiring the lock on the specified object, no other
thread will be able to execute the code block, or any other code requiring the same object lock, until
the lock is relinquished. This happens when the execution of the code block completes normally or an
uncaught exception is thrown.
 Synchronized block can be used to perform synchronization on any specific resource of the method.
 Suppose you have 50 lines of code in your method, but you want to synchronize only 5 lines, you can
use synchronized block.
 If you put all the codes of the method in the synchronized block, it will work same as the synchronized
method.
 Synchronized block is used to lock an object for any shared resource.
 Scope of synchronized block is smaller than the method.
 Object specification in the synchronized statement is mandatory. A class can choose to synchronize the
execution of a part of a method, by using the this reference and putting the relevant part of the
method in the synchronized block. The braces of the block cannot be left out, even if the code block
has just one statement.
class SmartClient
{
BankAccount account;
// …
public void updateTransaction()
{
synchronized (account) // (1)synchronized block
{
account.update(); // (2)
} } }
 NOTE:-In the previous example, the code at (2) in the synchronized block at (1) is
synchronized on the BankAccount object. If several threads were to concurrently
execute the method updateTransaction() on an object of SmartClient, the statement
at (2) would be executed by one thread at a time, only after synchronizing on the
BankAccount object associated with this particular instance of SmartClient.

Again, as in the following code:


class Outer // (1) Top-level Class
{
private double myPi; // (2)
protected class Inner // (3) Non-static member Class
{
public void setPi() // (4)
{
synchronized(Outer.this) // (5) Synchronized block on outer object
{
myPi = Math.PI; // (6)
}
}
}
}

128
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 NOTE:-Inner classes can access data in their enclosing context. An inner object might need to
synchronize on its associated outer object, in order to ensure integrity of data in the latter. This is
illustrated in the following code where the synchronized block at (5) uses the special form of the this
reference to synchronize on the outer object associated with an object of the inner class. This setup
ensures that a thread executing the method setPi() in an inner object can only access the private
double field myPi at (2) in the synchronized block at (5), by first acquiring the lock on the associated
outer object. If another thread has the lock of the associated outer object, the thread in the inner
object has to wait for the lock to be relinquished before it can proceed with the execution of the
synchronized block at (5). However, synchronizing on an inner object and on its associated outer
object are independent of each other, unless enforced explicitly,

 Below example shows how synchronized block and object locks are used to coordinate
access to shared objects by multiple threads.
public class SyncBlockExample extends Thread
{
static String[] msg = { "Beginner", "java", "tutorial,", ".,", "com","is", "the", "best" };
public SyncBlockExample(String id)
{
super(id);
}
public static void main(String[] args)
{
SyncBlockExample thread1 = new SyncBlockExample("thread1: ");
SyncBlockExample thread2 = new SyncBlockExample("thread2: ");
thread1.start();
thread2.start();
boolean t1IsAlive = true;
boolean t2IsAlive = true;
do
{
if (t1IsAlive &amp;&amp; !thread1.isAlive())
{
t1IsAlive = false;
System.out.println("t1 is dead.");
}
if (t2IsAlive &amp;&amp; !thread2.isAlive())
{
t2IsAlive = false;
System.out.println("t2 is dead.");
}
}
while (t1IsAlive || t2IsAlive);
}

129
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

void randomWait()
{
try
{
Thread.currentThread().sleep((long) (3000 * Math.random()));
}
catch (InterruptedException e)
{
System.out.println("Interrupted!");
}
}
public void run()
{
synchronized (System.out)
{
for (int i = 0; i &lt; msg.length; i++)
{
randomWait();
System.out.println(getName() + msg[i]);
}
}
}
}
Output
thread1: Beginner
thread1: java
thread1: tutorial,
thread1: .,
thread1: com
thread1: is
thread1: the
thread1: best
t1 is dead.
thread2: Beginner
thread2: java
thread2: tutorial,
thread2: .,
thread2: com
thread2: is
thread2: the
thread2: best
t2 is dead.

130
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 ANOTHER EXAMPLE 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
{
Thread.sleep(400);
}
catch(Exception e)
{
System.out.println(e);
} } }
}//end of the method
}
class MyThread1 extends Thread
{
Table t; public class TestSynchronizedBlock1
MyThread1(Table t) {
{ public static void main(String args[])
this.t=t; {
} Table obj = new Table();//only one object
public void run() MyThread1 t1=new MyThread1(obj);
{ MyThread2 t2=new MyThread2(obj);
t.printTable(5); t1.start();
} t2.start();
} }
class MyThread2 extends Thread }
{ Output:
Table t; 5
MyThread2(Table t) 10
{ 15
this.t=t; 20
} 25
public void run() 100
{ 200
t.printTable(100); 300
} 400
} 500

131
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 Example of synchronized block by using annonymous class:


//Program of synchronized block by using annonymous class
class Table
{
void printTable(int n)
{
synchronized(this) //synchronized block
{
for(int i=1;i<=5;i++)
{
System.out.println(n*i);
try
{
Thread.sleep(400);
}
catch(Exception e)
{
System.out.println(e);
} } }
}//end of the method
}
public class TestSynchronizedBlock2
{
public static void main(String args[])
{
final Table obj = new Table();//only one object
Thread t1=new Thread()
{
public void run()
{
obj.printTable(5);
} Output:
} 5
Thread t2=new Thread() 10
{ 15
public void run() 20
{ 25
obj.printTable(100); 100
} 200
} 300
t1.start(); 400
t2.start(); 500
}
}

132
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 Synchronized Keyword
To synchronize above program, we must serialize access to the shared display() method, making it available to
only one thread at a time. This is done by using keyword synchronized with display() method.
Syntax:- synchronized void display (String msg)
 Using Synchronised block
 If you have to synchronize access to object of a class that has no synchronized methods, and you
cannot modify the code. You can use synchronized block to use it.
class First
{
public void display(String msg)
{
System.out.print ("["+msg);
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
System.out.println ("]");
}
}
class Second extends Thread
{
String msg;
First fobj;
Second (First fp,String str)
{
fobj = fp;
msg = str;
start();
}
public void run()
{
synchronized(fobj) //Synchronized block
{ Output :
fobj.display(msg); [welcome]
} } } [new]
public class Syncro [programmer]
{
public static void main (String[] args)
{
First fnew = new First();
Second ss = new second(fnew, "welcome");
Second ss1= new second (fnew,"new");
Second ss2 = new second(fnew, "programmer");
} }
133
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

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

 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){ }
}
}
}

134
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

class MyThread1 extends Thread Output:


{ 1
public void run() 2
{ 3
Table.printTable(1); 4
} 5
} 6
class MyThread2 extends Thread 7
{ 8
public void run() 9
{ 10
Table.printTable(10); 10
} 20
} 30
class MyThread3 extends Thread 40
{ 50
public void run() 60
{ 70
Table.printTable(100); 80
} 90
} 100
class MyThread4 extends Thread 100
{ 200
public void run() 300
{ 400
Table.printTable(1000); 500
} 600
} 700
public class TestSynchronization4 800
{ 900
public static void main(String t[]) 1000
{ 1000
MyThread1 t1=new MyThread1();
MyThread2 t2=new MyThread2();
MyThread3 t3=new MyThread3();
MyThread4 t4=new MyThread4();
t1.start();
t2.start();
t3.start();
t4.start();
}
}

135
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 Example of static synchronization by annonymous class,in this example, we are using


annonymous class to create the threads.
class Table t1.start();
{ t2.start();
synchronized static void printTable(int n) t3.start();
{ t4.start();
for(int i=1;i<=10;i++) }
{ }
System.out.println(n*i); Output: 1
try 2
{ 3
Thread.sleep(400); 4
} 5
catch(Exception e){ } 6
} } } 7
public class TestSynchronization5 8
{ 9
public static void main(String[] args) 10
{ 10
Thread t1=new Thread() 20
{ 30
public void run() 40
{ 50
Table.printTable(1); 60
} 70
} 80
Thread t2=new Thread() 90
{ 100
public void run() 100
{ 200
Table.printTable(10); 300
} 400
} 500
Thread t3=new Thread() 600
{ 700
public void run() 800
{ 900
Table.printTable(100); 1000
} 1000
} 2000
Thread t4=new Thread() 3000
{ 4000
public void run() 5000
{ 6000
Table.printTable(1000); 7000
} 8000
} 9000
10000
136
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 SYNCHRONIZED THREADS:
In Java, the threads are executed separately to each other. These types of threads are called as asynchronous
threads. But there are two problems may be occurs with asynchronous threads.
1. Two or more threads share the similar resource (variable or method) while only one of them can
access the resource at one time.
2. If the producer and the consumer are sharing the same kind of data in a program then either
producer may make the data faster or consumer may retrieve an order of data and process it without
its existing.
3. Suppose, we have created two methods as increment( ) and decrement( ). which increases or
decreases value of the variable "count" by 1 respectively shown as:
public void increment( )
{
count++;
}
4. When the two threads are executed to access these methods (one for increment( ),another for
decrement( ) then both will distribute the variable "count". in that case, we can't be sure that what
value will be returned of variable "count".
5. To avoid this problem, Java uses monitor also known as “semaphore” to prevent data from being
corrupted by multiple threads by a keyword synchronized to coordinate them and intercommunicate
to each other. It is basically a mechanism which allows two or more threads to share all the available
resources in a sequential manner.
6. Java's synchronized is used to ensurethat only one thread is in a critical region. Critical region is a lock
area where only one thread is run (or lock) at a time. Once the thread is in its critical section, no other
thread can enter to that critical region. In that case, another thread will has to wait until the current
thread leaves its critical section.
 Lock:
 Lock term refers to the access approved to a particular thread that can access the shared resources. At
any given time, only one thread can hold the lock and thereby have access to the shared resource.
Every object in Java has build-in lock that only comes in action when the object has synchronized
method code. By associating a shared resource with a Java object and its lock, the object can act as a
guard, ensuring synchronized access to the resource. Only one thread at a time can access the shared
resource guarded by the object lock.
 Since there is one lock per object, if one thread has acquired the lock, no other thread can acquire the
lock until the lock is not released by first thread. Acquire the lock means the thread currently in
synchronized method and released the lock means exits the synchronized method.

137
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 Remember the following points related to lock and synchronization:


1. Only methods (or blocks) can be synchronized, Classes and variable cannot be synchronized. Each
object has just one lock.
2. All methods in a class need not to be coordinated. A class can have both synchronized and non-
synchronized methods.
3. If two threads wants to execute a synchronized method in a class, and both threads are using the
similar instance of the class to invoke the method then only one thread can execute the method at a
time.
4. If a class has both synchronized and non-synchronized methods, multiple threads can still access the
class's non-synchronized methods. If you have methods that don't access the data you're trying to
protect, then you don't need to synchronize them. Synchronization can cause a hit in several cases (or
even deadlock if used incorrectly), so you should be careful not to overuse it.
5. If a thread goes to sleep, it holds any locks it has—it doesn't let go them.
6. A thread can obtain more than one lock. For example, a thread can enter a synchronized method, thus
acquiring a lock, and then directly invoke a synchronized method on a different object, thus acquiring
that lock as well. As the stack unwinds, locks are unrestricted again.
7. You can synchronize a block of code rather than a method.
8. Constructors cannot be synchronized

138
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 Differences Between HashMap And HashTable In Java


HashMap and HashTable in java are two important data structures in the Collection Framework which have
some common things between them. Both implement Map interface. Both store the data in the form of key-
value pairs. Both use Hashing technique to store the elements. But, there also exist significant differences
between them. One important difference being the thread safety. HashMap is not thread safe where
asHashTable is thread safe.
 Differences Between HashMap And HashTable In Java :
1) Thread Safe
HashTable is internally synchronized. Therefore, it is very much safe to use HashTable in multi threaded
applications. Where as HashMap is not internally synchronized. Therefore, it is not safe to use HashMapin
multi threaded applications without external synchronization. You can externally
synchronizeHashMap using Collections.synchronizedMap() method.
2) Inherited From
Though both HashMap and HashTable implement Map interface, but they extend two different
classes.HashMap extends AbstractMap class where as HashTable extends Dictionary class which is the legacy
class in java.
3) Null Keys And Null Values
HashMap allows maximum one null key and any number of null values. Where as HashTable doesn’t allow
even a single null key and null value.
4) Traversal
HashMap returns only Iterators which are used to traverse over the elements
of HashMap.HashTable returns Iterator as well as Enumeration which can be used to traverse over the
elements ofHashTable.
5) Fail-Fast Vs Fail-Safe
Iterator returned by HashMap are fail-fast in nature i.e they throw ConcurrentModificationException if
theHashMap is modified after the creation of Iterator other than iterator’s own remove() method. On the
other hand, Enumeration returned by the HashTable are fail-safe in nature i.e they don’t throw any exceptions
if the HashTable is modified after the creation of Enumeration.
6) Performance
As HashTable is internally synchronized, this makes HashTable slightly slower than the HashMap.
7) Legacy Class
HashTable is a legacy class. It is almost considered as due for deprecation. Since JDK
1.5,ConcurrentHashMap is considered as better option than the HashTable.
8) Member Of Java Collection Framework
HashMap is a member of Java Collection Framework right from the beginning of its introduction in JDK 1.2.
But, HashTable was there before JDK 1.2. From JDK 1.2, it has been made to implement Mapinterface, making
it a member of collection framework.
9) When To Use What?
HashMap is always recommended if you don’t want thread safety. If you want thread safety, use
eitherConcurrentHashMap or make HashMap thread safe by using external synchronization
throughCollections.synchronizedMap() method. HashTable is not always recommended to use as it is
considered as a legacy class.

139
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

HashMap Vs HashTable In Java :


HashMap HashTable
HashMap is not synchronized and therefore it is not HashTable is internally synchronized and therefore it
thread safe. is thread safe.

HashMap allows maximum one null key and any


number of null values. HashTable doesn’t allow null keys and null values.

Iterators returned by the HashMap are fail-fast in Enumeration returned by the HashTable are fail-safe
nature. in nature.

HashMap extends AbstractMap class. HashTable extends Dictionary class.

HashTable returns both Iterator as well as


HashMap returns only iterators to traverse. Enumeration for traversal.

HashMap is fast. HashTable is slow.

HashMap is not a legacy class. HashTable is a legacy class.

HashMap is preferred in single threaded Although HashTable is there to use in multi threaded
applications. If you want to use HashMap in multi applications, now a days it is not at all preferred.
threaded application, wrap it using Because, ConcurrentHashMap is better option than
Collections.synchronizedMap() method. HashTable.

Compare between HashMap Vs HashTable In Java

140
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

HashMap vs HashSet In Java :

HASHSET HASHMAP

HashSet implements Set interface. HashMap implements Map interface.

HashSet stores the data as objects. HashMap stores the data as key-value pairs.

HashMap internally uses an array of Entry<K,


HashSet internally uses HashMap. V>objects.

HashMap doesn’t allow duplicate keys, but allows


HashSet doesn’t allow duplicate elements. duplicate values.

HashMap allows one null key and multiple null


HashSet allows only one null element. values.

Insertion operation requires two objects, key and


Insertion operation requires only one object. value.

HashSet is slightly slower than HashMap. HashMap is slightly faster than HashSet.

141
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 SIMILARITIES BETWEEN HASHMAP AND HASHTABLE IN JAVA :


1) Both store the data in the form of key-value pairs.
2) Both use Hashing technique to store the key-value pairs.
3) Both implement Map interface.
4) Both doesn’t maintain any order for elements.
5) Both give constant time performance for insertion and retrieval operations.

CONCLUSION
HashMap and HashSet, though they spell similar, are totally two different data structures in the Java
Collection Framework. HashMap is inherited from the Map interface where as HashSet is inherited from
the Set interface. The structure in which they hold the data is also different. HashMap holds the data as key-
value pairs where as HashSet holds the data as only objects. There are also some similarities exist between
them.

142
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

Q1) What is a Thread?


Ans) In Java, "thread" means two different things:
An instance of class java.lang.Thread.
A thread of execution.
An instance of Thread is just…an object. Like any other object in Java, it has variables and methods, and lives
and dies on the heap. But a thread of execution is an individual process (a "lightweight" process) that has its
own call stack. In Java, there is one thread per call stack—or, to think of it in reverse, one call stack per thread.
Even if you don't create any new threads in your program, threads are back there running.
The main() method, that starts the whole ball rolling, runs in one thread, called (surprisingly) the main thread.
If you looked at the main call stack (and you can, any time you get a stack trace from something that happens
after main begins, but not within another thread), you'd see that main() is the first method on the stack— the
method at the bottom. But as soon as you create a new thread, a new stack materializes and methods called
from that thread run in a call stack that's separate from the main() call stack.
Q2) What is difference between a thread and a process?
Ans)
1.Threads share the address space of the process that created it; processes have their own address.
2. Threads have direct access to the data segment of its process; processes have their own copy of the data
segment of the parent process.
3. Threads can directly communicate with other threads of its process; processes must use interprocess
communication to communicate with sibling processes.
4. Threads have almost no overhead; processes have considerable overhead.
5. New threads are easily created; new processes require duplication of the parent process.
6. Threads can exercise considerable control over threads of the same process; processes can only exercise
control over child processes.
7. Changes to the main thread (cancellation, priority change, etc.) may affect the behavior of the other threads
of the process; changes to the parent process do not affect child processes.
Q3) What are the advantages or usage of threads?
Ans)Threads support concurrent operations. For example,
• Multiple requests by a client on a server can be handled as an individual client thread.
• Long computations or high-latency disk and network operations can be handled in the background without
disturbing foreground computations or screen updates.
Threads often result in simpler programs.
• In sequential programming, updating multiple displays normally requires a big while-loop that performs
small parts of each display update. Unfortunately, this loop basically simulates an operating system scheduler.
In Java, each view can be assigned a thread to provide continuous updates.
• Programs that need to respond to user-initiated events can set up service routines to handle the events
without having to insert code in the main routine to look for these events.
Threads provide a high degree of control.
• Imagine launching a complex computation that occasionally takes longer than is satisfactory. A "watchdog"
thread can be activated that will "kill" the computation if it becomes costly, perhaps in favor of an alternate,
approximate solution. Note that sequential programs must muddy the computation with termination code,
whereas, a Java program can use thread control to non-intrusively supervise any operation.
Threaded applications exploit parallelism.
• A computer with multiple CPUs can literally execute multiple threads on different functional units without
having to simulating multi-tasking ("time sharing").
• On some computers, one CPU handles the display while another handles computations or database
accesses, thus, providing extremely fast user interface response times.

143
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

Q4)What are the two ways of creating thread?


Ans) There are two ways to create a new thread.
Extend the Thread class and override the run() method in your class. Create an instance of the subclass
and invoke the start() method on it, which will create a new thread of execution.
public class NewThread extends Thread
{
public void run()
{
// the code that has to be executed in a separate new thread goes here
}
public static void main(String [] args)
{
NewThread c = new NewThread();
c.start();
}
}
Implements the Runnable interface.The class will have to implement the run() method in the
Runnable interface. Create an instance of this class. Pass the reference of this instance to the Thread
constructor a new thread of execution will be created.
public class NewThread implements Runnable
{
public void run()
{
// the code that has to be executed in a separate new thread goes here
}
public static void main(String [] args)
{
NewThread c = new NewThread();
Thread t = new Thread(c);
t.start();
}
}
Q5) What are the different states of a thread's lifecycle?
Ans) The different states of threads are as follows:
New – When a thread is instantiated it is in New state until the start() method is called on the thread instance.
In this state the thread is not considered to be alive.
Runnable – The thread enters into this state after the start method is called in the thread instance. The thread
may enter into the Runnable state from Running state. In this state the thread is considered to be alive.
Running – When the thread scheduler picks up the thread from the Runnable thread’s pool, the thread starts
running and the thread is said to be in Running state.
Waiting/Blocked/Sleeping – In these states the thread is said to be alive but not runnable. The thread
switches to this state because of reasons like wait method called or sleep method has been called on the
running thread or thread might be waiting for some i/o resource so blocked. 5) Dead – When the thread
finishes its execution i.e. the run() method execution completes, it is said to be in dead state. A dead state can
not be started again. If a start() method is invoked on a dead thread a runtime exception will occur.

144
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

Q6) What is use of synchronized keyword?


Ans) synchronized keyword can be applied to static/non-static methods or a block of code. Only one thread at
a time can access synchronized methods and if there are multiple threads trying to access the same method
then other threads have to wait for the execution of method by one thread. Synchronized keyword provides a
lock on the object and thus prevents race condition.
E.g.
public void synchronized method(){}
public void synchronized staticmethod(){}
public void myMethod()
{
synchronized (this)
{
//synchronized keyword on block of code
}
}
Q7) What is the difference when the synchronized keyword is applied to a static method or
to a non static method?
Ans) When a synch non static method is called a lock is obtained on the object. When a synch static method is
called a lock is obtained on the class and not on the object. The lock on the object and the lock on the class
don’t interfere with each other. It means, a thread accessing a synch non static method, then the other thread
can access the synch static method at the same time but can’t access the synch non static method.
Q8) What is a volatile keyword?
Ans) In general each thread has its own copy of variable, such that one thread is not concerned with the value
of same variable in the other thread. But sometime this may not be the case. Consider a scenario in which the
count variable is holding the number of times a method is called for a given class irrespective of any thread
calling, in this case irrespective of thread access the count has to be increased so the count variable is declared
as volatile.
The copy of volatile variable is stored in the main memory, so every time a thread access the variable even for
reading purpose the local copy is updated each time from the main memory. The volatile variable also have
performance issues.
Q9) What is the difference between yield() and sleep()?
Ans) yield() method pauses the currently executing thread temporarily for giving a chance to the remaining
waiting threads of the same priority to execute. If there is no waiting thread or all the waiting threads have a
lower priority then the same thread will continue its execution. The yielded thread when it will get the chance
for execution is decided by the thread scheduler whose behavior is vendor dependent. If doesn't release the
lock on the objects acquired,sleep() allows the thread to go to sleep state for x milliseconds. When a thread
goes into sleep state it doesn’t releases the lock.
Q10) What is the difference between wait() and sleep()?
Ans)
wait() is a method of Object class. sleep() is a method of Object class.
sleep() allows the thread to go to sleep state for x milliseconds. When a thread goes into sleep state it doesn’t
release the lock. wait() allows thread to release the lock and goes to suspended state. The thread is only active
when a notify() or notifAll() method is called for the same object.
Q11) What is difference between notify() and notfiyAll()?
Ans) notify() wakes up the first thread that called wait() on the same object.
notifyAll() wakes up all the threads that called wait() on the same object. The highest priority thread will run
first.

145
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

Q12) What happens if a start method is not invoked and the run method is directly invoked?
Ans)If a thread has been instantiated but not started its is said to be in new state. Unless until a start() method
is invoked on the instance of the thread, it will not said to be alive. If you do not call a start() method on the
newly created thread instance thread is not considered to be alive. If the start() method is not invoked and the
run() method is directly called on the Thread instance, the code inside the run() method will not run in a
separate new thread but it will start running in the existing thread.
Q13) What happens when start() is called?
Ans) A new thread of execution with a new call stack starts. The state of thread changes from new to
runnable. When the thread gets chance to execute its target run() method starts to run.
Q14) If code running is a thread creates a new thread what will be the initial priority of the
newly created thread?
Ans) When a code running in a thread creates a new thread object, the priority of the new thread is set equal
to the priority of the thread which has created it.
Q15) When jvm starts up, which thread will be started up first?
Ans) When jvm starts up the thread executing main method is started.
Q16) What are the daemon threads?
Ans) Daemon thread are service provider threads run in the background,these not used to run the application
code generally.When all user threads(non-daemon threads) complete their execution the jvm exit the
application whatever may be the state of the daemon threads. Jvm does not wait for the daemon threads to
complete their execution if all user threads have completed their execution.
To create Daemon thread set the daemon value of Thread using setDaemon(boolean value) method. By
default all the threads created by user are user thread. To check whether a thread is a Daemon thread or a
user thread use isDaemon() method.
Example of the Daemon thread is the Garbage Collector run by jvm to reclaim the unused memory by the
application. The Garbage collector code runs in a Daemon thread which terminates as all the user threads
are done with their execution.
Q18) Can the variables or classes be Synchronized?
Ans) No. Only methods and blocks can be synchronized.
Q19) How many locks does an object have?
Ans) Each object has only one lock.
Q20) Can a class have both Synchronized and non-synchronized methods?
Ans) Yes a class can have both synchronized and non-synchronized methods.
Q21) What are the two ways to create the thread?
Ans :
1.by implementing Runnable
2.by extending Thread
Q22) Explain the advantages of threading?
Ans : Advantages of multithreading over multi-tasking:
1. Reduces the computation time.
2. Improves performance of an application.
3. Threads distribute the same address space so it saves the memory.
4. Context switching between threads is usually less costly than between processes.
5. Cost of communication between threads is comparatively low.

146
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

Q23) What are synchronized methods and synchronized statements?


Ans : Synchronized methods are methods that are used to control access to an object. A thread only executes
a synchronized method after it has acquired the lock for the method's object or class. Synchronized
statements are similar to synchronized methods. A synchronized statement can only be executed after a
thread has acquired the lock for the object or class referenced in the synchronized statement.
Q24) Explain the states of a tread?
Ans : There are five states:
New state – After the construction of Thread instance the thread is in this state but before the start()
method invocation. At this point, the thread is considered not alive.
Runnable (Ready-to-run) state – A thread start its life from Runnable state. A thread first enters runnable
state after the invoking of start() method but a thread can come again to this state after either running,
waiting, sleeping or coming back from blocked state also. On this state a thread is waiting for a turn on the
processor.
Running state – A thread is in running state that means the thread is presently executing. There are numerous
ways to enter in Runnable state but there is only one way to enter in Running state: the scheduler select a
thread from runnable pool.
Dead state – A thread can be considered dead when its run() method completes. If any thread comes on this
state that means it cannot ever run again.
Blocked - A thread can enter in this state because of waiting the resources that are hold by
another thread.
Q25)What is a thread?
Ans: In Java the Threadclass represents a single independent path of execution in a Java Virtual Machine.
When you run a Java program it implicitly starts a single thread of execution. The Threadclass enables
programmers to create additional threads and set them running. A number of threads may run in parallel, but
only one is actively executed at a given moment.
The Java runtime system uses fairly complex thread scheduling mechanisms to coordinate the execution of
threads, but this does not require privileged knowledge or detail level intervention by programmers.
Programmers can manage the high level creation, initiation and distribution of tasks amongst threads through
simple API methods.
The example below shows the simplest approach to thread creation and task execution; construct a new
Threadwith a Runnableargument and start it.
Q26)How to create one or more threads in Java?
Ans :
public class Demo implements Runnable
{
public static void main(String args[]) throws Throwable
{
Demo obj1 = new Demo();
Demo obj2 = new Demo();
new Thread(obj1).start();
new Thread(obj2).start();
// main thread is ending here,
// Thread-0 and Thread-1 continue to run.
}

147
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

public void run()


{
try
{
for (int i=0; i<5; i++)
{
System.out.println("thread "+Thread.currentThread().getName()+" step "+i); Thread.sleep(500);
}
}
catch (Throwable t) { }
}
}
Output:
C:\Java\jdk1.5.0_01\bin>java Demo
thread Thread-0 step 0
thread Thread-1 step 0
thread Thread-0 step 1
thread Thread-1 step 1
thread Thread-0 step 2
thread Thread-1 step 2
thread Thread-0 step 3
thread Thread-1 step 3
thread Thread-0 step 4
thread Thread-1 step 4
Q27) Implementation of the multithreads by extending Thread Class.
Ans:
class Thr1 extends Thread
{
Thr1(String s)
{
super(s);
start();
}
public void run()
{
for(int i=0;i<7;i++)
{
System.out.println("Name of thread:"+Thread.currentThread().getName());
try
{
Thread.sleep(1000);
}
catch(Exception e){ }
}
}

148
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

public class Demo


{
public static void main(String args[])
{
System.out.println("Thread Name :"+Thread.currentThread().getName()); Thr1 m1=new Thr1("Thread 1");
Thr1 m2=new Thr1("Thread 2");
}
}
Output:
C:\Java\jdk1.5.0_01\bin>java Demo
Thread Name :main
Name of thread:Thread 1
Name of thread:Thread 2
Name of thread:Thread 1
Name of thread:Thread 2
Name of thread:Thread 1
Name of thread:Thread 2
Name of thread:Thread 1
Name of thread:Thread 2
Name of thread:Thread 1
Name of thread:Thread 2
Name of thread:Thread 1
Name of thread:Thread 2
Name of thread:Thread 1
Name of thread:Thread 2
Q28) What is thread synchronization?
Ans:
 Handling threads inter communication
 Handling thread deadlock
 Major thread operations
Q29) If a class has a synchronized method and non-synchronized method, can multiple
threads execute the non-synchronized methods?
Ans)Yes. If a class has a synchronized and non-synchronized methods, multiple threads can access the non-
synchronixed methods.
Q30) If a thread goes to sleep does it hold the lock?
Ans) Yes when a thread goes to sleep, invoked by Thread.sleep(xx) it holds a lock.
Q31) Can a thread hold multiple locks at the same time?
Ans) Yes. A thread can hold multiple locks at the same time. Once a thread acquires a lock and enters into the
synchronized method / block, it may call another synchronized method and acquire a lock on another object.
Q32) Can a thread call multiple synchronized methods on the object of which it hold the
lock?
Ans) Yes. Once a thread acquires a lock in some object, it may call any other synchronized method of that
same object using the lock that it already holds. The locks are Reentarant.
Q33) Can static methods be synchronized?
Ans) Yes. Static methods are class methods and have only one copy of static data for the class, only one lock
for the entire class is required. Every class in java is represented by java.lang.Class instance. The lock on this
instance is used to synchronize the static methods.

149
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

Q34)Can two threads call two different static synchronized methods of the same class?
Ans) No. The static synchronized methods of the same class always block each other as only one lock per class
exists.So no two static synchronized methods can execute at the same time.
Q35)Does a static synchronized method block a non-static synchronized method?
Ans)No, the thread executing the static synchronized method holds a lock on the class and the thread
executing the non-satic synchronized method holds the lock on the object on which the method has been
called, these two locks are different and these threads do not block each other.
Q36) Once a thread has been started can it be started again?
Ans) No. Only a thread can be started only once in its lifetime. If you try starting a thread which has been
already started once an IllegalThreadStateException is thrown, which is a runtime exception. A thread in
runnable state or a dead thread can not be restarted.
Q37) When does deadlock occur and how to avoid it?
Ans) When a locked object tries to access a locked object which is trying to access the first locked object.
When the threads are waiting for each other to release the lock on a particular object, deadlock occurs .
Q38)What is a better way of creating multithreaded application? Extending Thread class or
implementing Runnable?
Ans) If a class is made to extend the thread class to have a multithreaded application then this subclass of
Thread can not extend any other class and the required application will have to be added to this class as it can
not be inherited from any other class. If a class is made to implement Runnable interface, then the class can
extend other class or implement other interface.
Q39) Can the start() method of the Thread class be overridden? If yes should it be
overridden?
Ans) Yes the start() method can be overridden. But it should not be overridden as it’s implementation in
thread class has the code to create a new executable thread and is specialised.
Q40) What are the methods of the thread class used to schedule the threads?
Ans) The methods are as follows:
 public static void sleep(long millis) throws InterruptedException
 public static void yield()
 public final void join() throws InterruptedException
 public final void setPriority(int priority)
 public final void wait() throws InterruptedException
 public final void notify()
 public final void notifyAll()
Q41) Which thread related methods are available in Object class?
Ans) The methods are:
 public final void wait() throws Interrupted exception
 public final void notify()
 public final void notifyAll()

150
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

Q42) Which thread related methods are available in Thread class?


Ans) Methods which are mainly used :
 public static void sleep(long millis) throws Interrupted exception
 public static void yield() public final void join() throws Interrupted exception
 public final void setPriority(int priority)
 public void start()
 public void interrupt()
 public final void join()
 public void run()
 public void resume()
Q43) List the methods which when called the thread does not release the locks held?
Ans) Following are the methods.
 join()
 sleep()
 yield()
Q44) List the methods which when called on the object the thread releases the locks held on
that object?
Ans) Following are the methods.
 notify()
 notifyAll()
 wait()
Q45) Does each thread has its own thread stack?
Ans) Yes each thread has its own call stack. For eg
 Thread t1 = new Thread();
 Thread t2 = new Thread();
 Thread t3 = t1;
In the above example t1 and t3 will have the same stack and t2 will have its own independent stack.
Q46) What is thread starvation?
Ans)In a multi-threaded environment thread starvation occurs if a low priority thread is not able to run or get
a lock on the resoruce because of presence of many high priority threads. This is mainly possible by setting
thread priorities inappropriately.

Q47) What is threadLocal variable?


Ans) ThreadLocal is a class. If a variable is declared as threadLocal then each thread will have a its own copy of
variable and would not interfere with the other's thread copy. Typical scenario to use this would be giving
JDBC connection to each thread so that there is no conflict.

 ThreadLocal class by JAVA API


public class ThreadLocal
{
public Object get();
public void set(Object newValue);
public Object initialValue();
}

151
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

//Implementation of ThreadLocal
public class ConnectionDispenser
{
private static class ThreadLocalConnection extends ThreadLocal
{
public Object initialValue()
{
return DriverManager.getConnection(ConfigurationSingleton.getDbUrl());
}
}
private static ThreadLocalConnection conn = new ThreadLocalConnection();
public static Connection getConnection()
{
return (Connection) conn.get();
}
}

Q48) What is Serialization?


Ans) Serializable is a marker interface. When an object has to be transferred over a network ( typically through
rmi or EJB) or to persist the state of an object to a file, the object Class needs to implement Serializable
interface. Implementing this interface will allow the object converted into bytestream and transfer over a
network.
Q49) What is use of serialVersionUID?
Ans) During object serialization, the default Java serialization mechanism writes the metadata about the
object, which includes the class name, field names and types, and superclass. This class definition is stored as a
part of the serialized object. This stored metadata enables the deserialization process to reconstitute the
objects and map the stream data into the class attributes with the appropriate type Everytime an object is
serialized the java serialization mechanism automatically computes a hash value. ObjectStreamClass's
computeSerialVersionUID() method passes the class name, sorted member names, modifiers, and interfaces
to the secure hash algorithm (SHA), which returns a hash value.The serialVersionUID is also called suid.
So when the serilaize object is retrieved , the JVM first evaluates the suid of the serialized class and
compares the suid value with the one of the object. If the suid values match then the object is said to be
compatible with the class and hence it is de-serialized. If notInvalidClassException exception is thrown.
Changes to a serializable class can be compatible or incompatible.
Following is the list of changes which are compatible:
 Add fields
 Change a field from static to non-static
 Change a field from transient to non-transient
 Add classes to the object tree
List of incompatible changes:
 Delete fields
 Change class hierarchy
 Change non-static to static
 Change non-transient to transient
 Change type of a primitive field
So, if no suid is present, inspite of making compatible changes, jvm generates new suid thus resulting in an
exception if prior release version object is used .
The only way to get rid of the exception is to recompile and deploy the application again.
152
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

 If we explicitly mention the sUid using the statement:


private final static long serialVersionUID = <integer value>
then if any of the metioned compatible changes are made the class need not to be recompiled. But for
incompatible changes there is no other way than to compile again.
Q50) What is the need of Serialization?
Ans) The serialization is used :-
 To send state of one or more object’s state over the network through a socket.
 To save the state of an object in a file.
 An object’s state needs to be manipulated as a stream of bytes.
Q51) Other than Serialization what are the different approach to make object Serializable?
Ans) Besides the Serializable interface, at least three alternate approaches can serialize Java objects:
For object serialization, instead of implementing the Serializable interface, a developer can implement the
Externalizable interface, which extends Serializable. By implementing Externalizable, a developer is
responsible for implementing the writeExternal() and readExternal() methods. As a result, a developer has sole
control over reading and writing the serialized objects.
XML serialization is an often-used approach for data interchange. This approach lags runtime
performance when compared with Java serialization, both in terms of the size of the object and the processing
time. With a speedier XML parser, the performance gap with respect to the processing time narrows.
Nonetheless, XML serialization provides a more malleable solution when faced with changes in the serializable
object.
Finally, consider a "roll-your-own" serialization approach. You can write an object's content directly via
either the ObjectOutputStream or the DataOutputStream. While this approach is more involved in its initial
implementation, it offers the greatest flexibility and extensibility. In addition, this approach provides a
performance advantage over Java serialization.
Q52) Do we need to implement any method of Serializable interface to make an object
serializable?
Ans) No. Serializable is a Marker Interface. It does not have any methods.
Q53) What happens if the object to be serialized includes the references to other serializable
objects?
Ans) If the object to be serialized includes references to the other objects, then all those object’s state also will
be saved as the part of the serialized state of the object in question. The whole object graph of the object to
be serialized will be saved during serialization automatically provided all the objects included in the object’s
graph are serializable.
Q54) What happens if an object is serializable but it includes a reference to a non-
serializable object?
Ans- If you try to serialize an object of a class which implements serializable, but the object includes a
reference to an non-serializable class then a ‘NotSerializableException’ will be thrown at runtime.
public class NonSerial
{
//This is a non-serializable class
}
public class MyClass implements Serializable
{
private static final long serialVersionUID = 1L;
private NonSerial nonSerial;

153
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

MyClass(NonSerial nonSerial)
{
this.nonSerial = nonSerial;
}
public static void main(String [] args)
{
NonSerial nonSer = new NonSerial();
MyClass c = new MyClass(nonSer);
try
{
FileOutputStream fs = new FileOutputStream("test1.ser");
ObjectOutputStream os = new ObjectOutputStream(fs);
os.writeObject(c);
os.close();
}
catch (Exception e)
{
e.printStackTrace();
}
try
{
FileInputStream fis = new FileInputStream("test1.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
c = (MyClass) ois.readObject();
ois.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
On execution of above code following exception will be thrown;
 java.io.NotSerializableException: NonSerial
 at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java)
Q55) Are the static variables saved as the part of serialization?
Ans) No. The static variables belong to the class are not the part of the state of the object so they are not
saved as the part of serialized object.
Q56)What is a transient variable?
Ans) These variables are not included in the process of serialization and are not the part of the object’s
serialized state.

Q57) What will be the value of transient variable after de-serialization?


Ans) It’s default value.
e.g. if the transient variable in question is an int, it’s value after deserialization will be zero.

154
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

public class TestTransientVal implements Serializable


{
private static final long serialVersionUID = -22L;
private String name;
transient private int age;
TestTransientVal(int age, String name)
{
this.age = age;
this.name = name;
}
public static void main(String [] args)
{
TestTransientVal c = new TestTransientVal(1,"ONE");
System.out.println("Before serialization:" + c.name + " "+ c.age);
try
{
FileOutputStream fs =new FileOutputStream("testTransient.ser");
ObjectOutputStream os = new ObjectOutputStream(fs);
os.writeObject(c);
os.close();
}
catch (Exception e)
{
e.printStackTrace();
}
try
{
FileInputStream fis =new FileInputStream("testTransient.ser");
ObjectInputStream ois =new ObjectInputStream(fis);
c = (TestTransientVal) ois.readObject();
ois.close();
}
catch (Exception e)
{
e.printStackTrace();
}
System.out.println("After de-serialization:" + c.name +" "+ c.age);
}
}
Result of executing above piece of code –
 Before serialization: - Value of non-transient variable ONE Value of transient variable 1
 After de-serialization:- Value of non-transient variable ONE Value of transient variable 0
Explanation –
The transient variable is not saved as the part of the state of the serailized variable, it’s value after de-
serialization is it’s default value.

155
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

Q59) Does the order in which the value of the transient variables and the state of the object
using the defaultWriteObject() method are saved during serialization matter?
Ans) Yes, while restoring the object’s state the transient variables and the serializable variables that are stored
must be restored in the same order in which they were saved.
Q60) How can one customize the Serialization process? or What is the purpose of
implementing the writeObject() and readObject() method?
Ans) When you want to store the transient variables state as a part of the serialized object at the time of
serialization the class must implement the following methods –
private void wrtiteObject(ObjectOutputStream outStream)
{
//code to save the transient variables state
//as a part of serialized object
}
private void readObject(ObjectInputStream inStream)
{
//code to read the transient variables state
//and assign it to the de-serialized object
}
public class TestCustomizedSerialization implements Serializable
{
private static final long serialVersionUID =-22L;
private String noOfSerVar;
transient private int noOfTranVar;
TestCustomizedSerialization(int noOfTranVar, String noOfSerVar)
{
this.noOfTranVar = noOfTranVar;
this.noOfSerVar = noOfSerVar;
}
private void writeObject(ObjectOutputStream os)
{
try
{
os.defaultWriteObject();
os.writeInt(noOfTranVar);
} catch (Exception e)
{
e.printStackTrace();
}
}
private void readObject(ObjectInputStream is)
{
try
{
is.defaultReadObject();
int noOfTransients = (is.readInt());
}

156
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

catch (Exception e)
{
e.printStackTrace();
}
}
public int getNoOfTranVar()
{
return noOfTranVar;
}
EXPLAIN:-
 The value of transient variable ‘noOfTranVar’ is saved as part of the serialized object manually by
implementing writeObject() and restored by implementing readObject().
 The normal serializable variables are saved and restored by calling defaultWriteObject() and
defaultReadObject()respectively. These methods perform the normal serialization and de-sirialization
process for the object to be saved or restored respectively.
Q61) If a class is serializable but its superclass in not, what will be the state of the instance
variables inherited from super class after deserialization?
Ans) The values of the instance variables inherited from superclass will be reset to the values they were given
during the original construction of the object as the non-serializable super-class constructor will run.
E.g.
public class ChildSerializable extends ParentNonSerializable implements Serializable
{
private static final long serialVersionUID = 1L;
String color;
ChildSerializable()
{
this.noOfWheels = 8;
this.color = "blue";
}
}
public class SubSerialSuperNotSerial
{
public static void main(String [] args)
{
ChildSerializable c = new ChildSerializable();
System.out.println("Before : - " + c.noOfWheels + " "+ c.color);
try
{
FileOutputStream fs = new FileOutputStream("superNotSerail.ser");
ObjectOutputStream os = new ObjectOutputStream(fs);
os.writeObject(c);
os.close();
}
catch (Exception e)
{
e.printStackTrace();
}

157
JAVA PART=24 CHIRADIP ASU=9874488038/9903616736

try
{
FileInputStream fis = new FileInputStream("superNotSerail.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
c = (ChildSerializable) ois.readObject();
ois.close();
}
catch (Exception e)
{
e.printStackTrace();
}
System.out.println("After :- " + c.noOfWheels + " "+ c.color);
}
}
Result on executing above code –
Before : - 8 blue
After :- 4 blue

158
CHIRADIP BASU:-- 9903616736 / 9874488038

159

You might also like