Java Threading SN U4
Java Threading SN U4
JAVA THREADS
THREAD
• Thread is a single line of execution
• It is a single independent path of execution within a progam
• It executes program statement one by one.
LIFE CYCLE OF THREADS (THREAD STATES)
1. New born state (new state)
2. Runnable state
3. Running state
4. Blocked state
5. Dead state (final state)
NOTE
• It is an important to note that, Thread is always live in any one of the
five states.
1. NEW STATE
• Once Thread object is created, then it is said to be new state (new
born state) (Creating an object for thread class)
Example
Test obj=new Test();
2. RUNNABLE STATE
• Here, thread is ready for execution and it is waiting for availability of
the processor(all threads in queue)
• If two or more threads or all the threads are equal priority, then they
will be given the time-slots for execution by the thread scheduler.
Example
obj.start() ready to start the thread execution
1
| Java Threads |
3. RUNNING STATE
• Execution of thread
• The processor has given the time to the thread for execution
Example
public void run()
{
// user code executing thread
}
4. BLOCKED STATE
• Here thread is blocked for some situations
• The running thread may lose its control in the some situaions.
• Here thread is not runnable state / not dead state. So it can run again.
Blocked Methods
• suspend() : block thread, until further orders
• wait() : block thread, until certain event(condition) occurs
• sleep(time) : block thread, for a specific period of time interval
1. suspend()
• Here, running thread is blocked, until further orders
• At this stage, thread’s execution will be temporialy stopped until calling
the resume() method
• This is not runnable and not dead state
• Check the thread status, before calling this method
• After calling resume() method, the thread will return the control to
runnable state.
2
| Java Threads |
o o o
2. sleep(time)
• Here, running thread will be blocked for specific period of time interval
(time in milli-seconds)
• The thread will return the control to runnable state, when the specific
time interval is elapsed.
o o o
Example
obj.sleep(500); // block a thead till 500 ms
3
| Java Threads |
3. wait()
• Block a thread, until some event occurs
• This is can be done by using wait() method
• The thread will return the control to runnable state, when a particular
event is finished.
o o o
5. DEAD STATE
• This is the final state (stage) in thread life cycle
• Every thread has life cycle
• It is classified as two types. They are
1. Nature death
2. Pre-mature death
Nature Death (Implicit Dead)
• Once thread operations are over, then it comes to end
• Whenever running thread will complete its task, then it will go to end
state. This is called as nature death
Pre-mature Death (Explicit Dead)
• First, check the status of thread, before to kill
• A thread can be killed explicitly at any state by sending the stop
message. This is called as pre-mature death.
4
| Java Threads |
Example
obj.stop()
Package Support
• The package java.lang.* provides the full support (using built-in
classes) for the operations of thread
• This is a default package in java.
Package
java.lang.*;
STATIC PROPERTIES
• It is possible to implement priority based thread tasks using static
priorites such as normal(default), minimum, maximum.
1. NORM_PRIORITY
• It is a static property of the Thread class
• Here, the default priority is assigned to a thread
• Value : 5
• Return Type : int
2. MAX_PRIORITY
• It is a static property of the Thread class
• Here, maximum prioroity level will be assigned to thread
• Value : 10
• Return Type : int
3. MIN_PRIORITY
• It is a static property of the Thread class
• Here, minimum prioroity level will be assigned to thread
• Value : 0
• Return Type : int
5
| Java Threads |
6
| Java Threads |
2. getName()
• It is an instance method of the thread object
• This method will return the name of currently executing thread (name
of the running thread)
• Return Type : String
3. getPriority()
• It is an instance method of the thread object
• It returns priority of currently executing thread (running thread)
• Return Type : int
4. isAlive()
• It is an instance method of the thread object
• This method will check whether thread is alive or not
• Returns true, if the thread is alive
• Returns false, if the thread is not alive
• Return Type : Boolean
5. join()
• It is an instance method of the thread object
• This method is used to join two or more threads (Other thread should
wait until current thread has to die).
• Return Type : void
6. resume()
• It is an instance method of the thread object
• It is used to resume the already suspended thread
• Return Type : void
7. run()
• It is an instance method of the thread object
• It contains the logic of the thread (action of thread)
• Changing runnable state to running state
7
| Java Threads |
11. suspend()
• It is an instance method of the thread object
• It suspends current thread
• Return Type : void
12. toString()
• It is an instance method of the thread object
• Returns a string representation of this thread, including the thread's
name, priority, and thread group.
• Return Type : String
13. wait()
• It is an instance method of the thread object
• It is used to block (wait) the thread, until some event occurs
• Return Type : void
14. setName(String name)
• It is an instance method of the thread object
• It is used to set the name to current thread
• Return Type : void
8
| Java Threads |
THREAD CREATION
• In java, thread is created in two ways. They are
1. By Extendng the Thread class (built-in class)
2. By Implemeting the Runnable interface (built-in interface)
9
| Java Threads |
Where,
Sub_Thread ➔ Name of the sub class thread
run() ➔ instance method, that contains the body of the thread
run()
• It is built-in method of Thread class
• It contains the logic of thread. Here user has to write the code
logic.
THREAD CALLING
• Once the thread is created, it can be started by creating an instance of
a thread and than calling the start() method (buil-in method)
Syntax
10
| Java Threads |
3. Create a thread object and call the start() method to initiate the
thread execution.
Example
Test t1=new Test();
t1.start(); // call the run() method
NOTE
• Once thread is created, then there will be two threads running in the
program. They are
1. the main thread
2. t1 thread.
11
| Java Threads |
I. THREAD CREATION
(BY EXTENDING THE THREAD CLASS)
1. SOURCE CODE
package jt;
// creating a new thread class by extending built-in super class Thread
public class JSingleThread extends Thread
{
// running state: logic of the thread
Running State
public void run()
{
System.out.println("Good Morning...");
}
public static void main(String[] args) Newborn State
{
System.out.println("---------------------------------------");
System.out.println("\tSingle Thread");
System.out.println("---------------------------------------");
// new born state: derived class object creation
JSingleThread born=new JSingleThread();
// runnable state: ready to execute the thread
born.start();
}
}
Runnable State
12
| Java Threads |
2. OUTPUT
Where,
Sub_Thread ➔ Name of the sub class thread
run() ➔ instance method, that contains the body of the thread.
13
| Java Threads |
THREAD CALLING
• Once the thread is created, it can be started by creating an instance of
a thread and than calling the start() method (buil-in method)
Syntax
Sub_Thread obj=new Sub_Thread()
// convert normal class to thread class using constructor
Thread t=new Thread(obj);
t.start(); inititates an activity
Explanation
• The 1st line creates the object of the sub class
• The 2nd line creates the object of Thread class and attach the object of
the sub class as argument to the constructor of the Thread class
• The 3rd line invokes the thread by calling the start() method.
STEPS FOR CREATING A THREAD USING RUNNABLE INTERFACE
1. Create a new class which implements the super interface Runnable
Example
class Test implements Runnable
{
// user code
}
15
| Java Threads |
16
| Java Threads |
2. OUTPUT
JAVA MULTITHREADING
(CONCURRENT PROGRAMMING)
LIGHTWEGHT THREADS
• If all the threads are executed in a same address space, than it is
called as lightweight thread.
MULTITHREADING
• Doing more than one job(process) at the same time (Executing more
than one thread at a time)
• Process of executing multiple threads simultaneously is called
as multithreading
• Process is a program in execution (executing the program)
• Parallel execution of multiple tasks
• Two or more programs / applications / processes are running
concurrently in a computer is called as multitasking
• Every thread in java is created and controlled by the
java.lang.Thread class
IMPORTANT NOTE
• A java program can have many threads (multithreading) and these
threads can run concurrently, either synchronously or
asynchronously.
17
| Java Threads |
Multitasking
• Ability to execute more than one task at the same time is known as
multitasking.
Multithreading
• It is a process of executing multiple threads simultaneously.
Multithreading is also known as Thread-based Multitasking.
Multiprocessing
• It is same as multitasking, however in multiprocessing more than one
CPUs are involved. On the other hand one CPU is involved in
multitasking.
Parallel Processing
• It refers to the utilization of multiple CPUs in a single computer system.
Multithreading
Synchronous Asynchronous
Process Process
18
| Java Threads |
19
| Java Threads |
MULTITASKING (MULTITHREADING)
• Doing more than one job at a time
Example
Company
22
| Java Threads |
{
out.println("Welcome to Chennai city, Inida");
}
}
catch(Exception e)
{
out.println("Thread Interrupted...");
}
}
}
// separate main class
public class MultiThreads
{
// get the thread property
static void Tname()
{
// get currently executing thread by calling thread()
Thread t=Thread.currentThread();
String name=t.getName();
out.println("Thread Name \t: " +name);
}
static public void main(String[] args)
{
out.println("======================================");
out.println("\tMultiThreading is running in Synchrounous way ");
out.println("=====================================");
// new born state: Extended Thread class object creation
Salem slm=new Salem();
Sydney syd=new Sydney();
25
| Java Threads |
26
| Java Threads |
2. OUTPUT
NOTE
• It is an important to note that, we can’t expect the same output
like above picture in the multithreading. It may vary from JVM to
JVM.
27
| Java Threads |
28
| Java Threads |
MultiThreads.Tname();
try
{
for(int i=0;i<5;i++)
{
// blocked state: block a thread till 300 milliseconds
Thread.sleep(300);
out.println("Welcome to Chennai city, Inida");
}
}
catch(Exception e)
{
out.println("Thread Interrupted...");
}
}
} Display the name of currently
// separate main class executing thread by using getName()
public class MultiThreads
{
static void Tname()
{
Thread t=Thread.currentThread();
String name=t.getName();
out.println("Thread Name \t: " +name);
}
static public void main(String[] args)
{
out.println("========================================");
out.println("\tMultiThreading is running in Asynchrounous way ");
30
| Java Threads |
out.println("========================================");
// NEW BORN STATE: EXTENDED THREAD CLASS OBJECT
CREATION
Salem slm=new Salem();
Sydney syd=new Sydney();
Chennai che=new Chennai();
// set the new name for the thread using setName() method
slm.setName("Salem");
syd.setName("Sydney");
che.setName("Chennai");
// RUNNABLE STATE: READY TO EXECUTE THE THREADS
slm.start();
che.start();
syd.start();
}
}
31
| Java Threads |
2. OUTPUT
32
| Java Threads |
JOINING THREADS
• Join() method is used to join the two or more threads.
Existing problem
• In asynchronous mode, all the threads are running in parallel.
• Each thread need not wait for others.
Proposed System (Joining Threads)
• To overcome the above problem, java provides the new solution
called as joining threads
• In same asynchronous mode, each thread should wait, while others
finish their execution.
• This is done with help of instance method called join()
join()
• This built-in instance method is mainly used to join the two or more
threads
• It is an important to note that, this method must be handled by try-
catch blocks or declared thrown using throws clause.
• Return type: void
33
| Java Threads |
{
try
{
for(int i=0;i<5;i++)
{
// blocked state : block a thread till 700 ms
Thread.sleep(700);
System.out.println("Executing 2nd thread...");
}
}
catch(Exception e)
{
System.out.println("Thread Interrupted...");
}
}
}
// separate main class
public class Eproblem
{
public static void main(String[] args)
{
System.out.println("===============================");
System.out.println("\tSimple MultiThreading ");
System.out.println("===============================");
// NEWBORN STATES
One t1=new One();
Second t2=new Second();
// RUNNABLE STATE
t1.start();
35
| Java Threads |
// RUNNABLE STATE
t2.start();
}
}
2. OUTPUT
36
| Java Threads |
System.out.println("=======================================");
System.out.println("\tMultiThreading with join method ");
System.out.println("=======================================");
// newborn states
38
| Java Threads |
39
| Java Threads |
2. OUTPUT
EXPLANATION
• The join() method makes the caller to wait till the current thread
finishes their execution.
• In this case, main thread and 2nd thread should wait, until the 1st thread
finishes their execution, before starting the 2nd thread and main thread.
• So when this program is executed, it will display asynchronous output.
40
| Java Threads |
THREAD PRIORITY
• Generally all the threads are running concurrently but not at the
same time.
• In java, we can specify the priority of each thread relative to other
threads.
• Those threads having higher priority get greater access to available
resources than lower priority threads.
• If two threads having equal priority (same priority), then thread
scheduler (processors) are given the time-slots to each thread for
executing its own method. [processor chooses one of them to run in a
round-robin fashion (1st come 1st server manner)]
• If we explicitly set the thread priority to Highest, then setting to highest
thread is executed first and then next thread (2nd thread) is executed.
BUILT-IN INSTANCE METHODS
1. setPriority(int no)
• This built-in instance method is used to set the priority of a thread
• This method takes only one argument. The argument is an integer
• Return type: void
2. getPriority()
• This built-in instance method is used to get the priority of a thread
• This method does not take any arguments
• Return type: int
STATIC PROPERTIES
• The following static final integers constants are defined in the Thread
class.
MIN_PRIORITY
• Lowest priority
• Code :0
41
| Java Threads |
NORM_PRIORITY
• Default priority
• Code :5
MAX_PRIORITY
• Highest priority
• Code : 10
NOTE
• The priority of an individual thread can be set to any integer value
between minimum and maximum range.
42
| Java Threads |
// RUNNING STATE
public void run()
{
for(int i=0;i<3;i++)
out.println("Ramesswaram express is running...");
}
}
// creating Perlcity thread (sub thread 3)
class Perlcity extends Thread
{
// RUNNING STATE
public void run()
{
for(int i=0;i<3;i++)
out.println("Muthunagar superfast express is running...");
}
}
// seprate main class
public class MT_TPriority
{
// main thread
static public void main(String[] args)
{
out.println("==========================================");
out.println("\tMultiThreading with Thread Priorities ");
out.println("==========================================");
// NEW BORN STATES : OBJECT CREATION FOR DERIVED CLASSES
Perlcity pc=new Perlcity();
Rameswaram ram=new Rameswaram();
43
| Java Threads |
44
| Java Threads |
2. OUTPUT
45
| Java Threads |
THREAD SYNCHRONIZATION
Shared data
• If two or more methods can access same data, then it is said to be
shared data.
Synchronization
• If two or more threads can access the same method or shared data,
then the result can be unexpected. This process is called as
synchronization.
• In such situations, more than one thread can try to access the
same method and data at the same time or a thread can try to
access the method that is currently in use by another thread.
• This may lead to serious problems. Java enables us to overcome this
problem by using a technique called synchronization
Syntax
synchronized void run()
{
// user code
}
(OR)
synchronized(lock-object)
{
// user code
}
Example
synchronized(this) locking current object using this operator
{
// code
}
46
| Java Threads |
CASE 2
47
| Java Threads |
CASE 3
48
| Java Threads |
int bal=amt;
amt=amt+money;
// BLOCKED STATE
try
{
Thread.sleep(500);
System.out.println(Thread.currentThread().getName()+": ");
System.out.println("Balance\t: "+bal);
System.out.println("Amount credited successfully ...");
System.out.println("Balance After Deposit\t: "+amt);
}
catch(Exception e)
{
e.printStackTrace();
49
| Java Threads |
}
}
// main method
public static void main(String[] args)throws Exception
{
System.out.println("-------------------------------------------------");
System.out.println("\tMultithreading using Synchronization");
System.out.println("-------------------------------------------------");
JBank t1=new JBank();
JBank t2=new JBank();
JBank t3=new JBank();
// setting the names to threads
t1.setName("t1");
t2.setName("t2");
t3.setName("t3");
// RUNNABLE STATES
t1.start();
t2.start();
t3.start();
}
}
50
| Java Threads |
2. OUTPUT
NOTE
• In the above multithreading(asynchronous method) program, the
synchronized method / block allows only one thread at a time to
execute its operations.
• The remaining threads should wait for the current thread to finish its
task.
51