0% found this document useful (0 votes)
6 views51 pages

Java Threading SN U4

threadin in java
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)
6 views51 pages

Java Threading SN U4

threadin in java
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/ 51

| Java Threads |

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

Running Runnable Suspended


resume()
Example
obj.suspend()

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

Running Runnable Sleeping


Syntax
Thread.sleep(int time); // time in milli-seconds

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

Running Runnable Waiting


Example
obj.wait()

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 |

STATIC METHODS OF THREAD CLASS


1. activeCount()
• It is a static method of the Thread class
• It returns the total number of active threads in the current thread’s
thread object
• Return Type : int
2. currentThread()
• It is a static method of the Thread class
• It returns a reference to the currently executing thread object
• Return Type : Thread
3. sleep(long milliseconds)
• It is a static method of the Thread class
• It blocks a thread for the specified period of time interval(milliseconds)
• Return Type : void
4. yield()
• It is a static method of the Thread class
• It is used to temporialy pause a currently executing thread object
(running thread) and allow other threads to execute
• Return Type : void
INSTANCE METHODS OF THREAD CLASS
1. getId()
• It is an instance method of the thread object
• Once the thread is creaed, then it will return the thread ID
• The thread ID is a unique and positive long number
• When a thread is terminated, this thread ID may be reused.
• Return Type : long

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 |

• Return Type : void


8. start()
• It is an instance method of the thread object
• It used to begin the thread execution. The JVM will call the run()
method current / this thread, if start() is called
• Return Type : void
9. stop()
• It is an instance method of the thread object
• It is used to kill the thread
• Return Type : void

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 |

15. setPriority(int newPriority)


• It is an instance method of the thread object
• This method is used to set or modify the priority level to current thread
object
• Return Type : void
SINGLE THREADED PROGRAM
• A thread is similar to a program that has a single flow of control
• It has beginning, a body, an end and executes the commands
sequentially
• In fact, all java main program can be called as single threaded
program
• Every program will have at least one thread (main function)
Single Threaded Program
class sony
{
…………. Beginning
…………. Single-threaded body of
………….
…………. execution
………….
…………. End
………….
}

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 |

BY EXTENDING THE THREAD CLASS


• Here, thread is created by extending the super class called Thread
• Thread is actually predefined class and it is available in java.lang.*
package
• The thread class provides a lot of life cycle methods to the derived
class (new class)
Syntax
class Sub_Thread extends Thread
{
public void run()
{
// body of the thread
}
}

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

Sub_Thread obj=new Sub_Thread()


obj.start();  inititates an activity

10
| Java Threads |

STEPS FOR CREATING A THREAD USING SUPER CLASS THREAD


1. Create new class which extends the super class Thread
Example
class Test extends Thread
{
// user code
}

2. Implement the run() method, that is responsible for executing the


sequence of code that, the thread will execute.
Example
class Test extends Thread
{
public void run()
{
// user code
}
}

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

BY IMPLEMENTING THE RUNNABLE INTERFACE


• Threads can also be created by creating a class which implements the
Runnable interface
• The Runnable interface is a built-in interface in java
SYNTAX
class Sub_Thread implements Runnable
{
public void run()
{
// body of the thread
}
}

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
}

2. Implement the run() method


Example
class Test implements Runnable
{
public void run()
{
// user code
}
}
14
| Java Threads |

3. Here derived class is not yet thread class. So convert current


derived class to thread class and create a thread object (mapping
derived class to thread class) and then call the start() method to
initiate the thread execution.
Example
// create an object of the derived class
Test obj=new Test();
// still now current derived class is not a Thread class. So
convert current derived class to thread using thread’s
constructor
Thread t1=new Thread(obj);
// execute the thread by calling the run() method
t1.start();

15
| Java Threads |

II. THREAD CREATION


(BY IMPLEMENTING RUNNABLE INTERFACE)
Super Interface Used: Runnable
1. SOURCE CODE
package jt;
// creating a new thread class by implements the built-in super
interface Runnable
public class JSingleThread1 implements Runnable
{
// running state : logic of the thread
public void run()
{
System.out.println("Welcome to Chennai...");
}
public static void main(String[] args)
{
System.out.println("----------------------------------------------------------");
System.out.println("\tSingle Thread via Runnable Interface");
System.out.println("----------------------------------------------------------");
// convert derived class to thread class
JSingleThread1 obj=new JSingleThread1();
// new born state : derived class object creation
Thread nborn=new Thread(obj);
// runnable state : ready to execute the thread
nborn.start();
}
}

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

MULTITHREADING WITH SYNCHRONOUS PROCESS


• Here client can do only one job at the same time. (Other threads
shoud wait for current thread will finish its execution)
• Client should wait for one job is to complete and cann’t concentrate
another job at the same time.
• It is an important to note that, one thread need to wait untill another
thread has to complete.

18
| Java Threads |

MULTITHREADING WITH ASYNCHRONOUS PROCESS


• Here client can do many jobs at the same time.
• One thread need not wait for another thread to finish its task.

1. A MULTITHREADED WITH SYNCHRONOUS MODE


Main Thread
-----------------------
-----------------------
-----------------------
-----------------------

start start start

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


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

Thread 1 Thread 2 Thread 3

19
| Java Threads |

2. A MULTITHREADED WITH ASYNCHRONOUS MODE


Main Thread
-----------------------
-----------------------
-----------------------
-----------------------

start start start

--------------------- ----------------------- switching -----------------------


switching
--------------------- ----------------------- -----------------------
--------------------- ----------------------- -----------------------
--------------------- ----------------------- -----------------------
--------------------- ----------------------- -----------------------
----------
Thread 1 Thread 2 Thread 3

MULTITASKING (MULTITHREADING)
• Doing more than one job at a time
Example
Company

Accounting Admin Sales

• Here the company has three departments / sections


• If a company to run properly, then all these departments have to
work simultaneously
• If any one of these departments fail, then company can’t functions.
20
| Java Threads |

• A program can have many threads in multithreaded programs, each


thread can work at different times (asynchronously), one after the
other (sequentially) or at the same time (synchronously).
NOTE
• The main thread is actually the main method module, which is
designed to create and start the other three threads namly 1, 2 & 3
• Once job is initiated by the main thread, the other threads 1,2 & 3
will run concurrently and share the resources jointly.
• It is important to note that, main thread can randomly start the
sub threads in multithreading application.
• The ability of a language to support multithreads is referred to as
concurrency
• It is important to note that, threads running in parallel does not really
mean that, they actually run at the same time. Since all the threads
are running on a single processor, the execution flow is shared
between the threads.
• The java interpreter (JVM) handles the switching of control between
the threads in such a way that it appears they are running
concurrently.
THREAD SCHEDULER
• Many computers have only one CPU, so threads must share the
CPU with other threads.
• Execution of multiple threads on a single CPU in some order is
called as scheduling.
• It is a part of JVM that decides which thread should run in
multitheading concept.
• The Java platform supports the scheduling algorithm called fixed-
priority scheduling. Each thread has a numeric priority
between MIN_PRIORITY(0) and MAX_PRIORITY(10)
• At any given time, when multiple threads are ready to be executed,
the highest-priority thread is chosen for execution.
• When we have multiple threads, then which thread will get a chance
is decided by thread scheduler.
21
| Java Threads |

• There is no guarantee that, which runnable thread will be chosen to


run by the thread scheduler.
• Only one thread can be allowed to run in a single process.
• It is an important to note that, thread scheduler will schedule waiting
for threads based on some priorities the threads having high priority
will get a chance first.
• We can't expect exact methodologies followed by thread scheduler.
It may vary from JVM to JVM dependent. That's why, we are not
able to tell the exact output in multithreading concepts.
• Thread schedular has only to decide the order for waiting threads
(remaining threads) to execute in the multithreading.

22
| Java Threads |

III. EXAMPLE OF MULTITHREADING


(SYNCHRONOUS WAY)
1. SOURCE CODE
package multithreading;
import static java.lang.System.*;
// creating salem thread by extending thread class
class Salem extends Thread
{
// RUNNING STATE: CONTAINS THE LOGIC OF THREAD
public void run()
{
// call the thread properties: get name of the thread
MultiThreads.Tname();
try
{
for(int i=0;i<5;i++)
{
out.println("Welcome to Salem city, Inida");
}
}
catch(Exception e)
{
out.println("Thread Interrupted...");
}
}
}
// creating sydney thread
class Sydney extends Thread
{
23
| Java Threads |

// RUNNING STATE : CONTAINS THE LOGIC OF THREAD


public void run()
{
// call the thread properties: get name of the thread
MultiThreads.Tname();
try
{
for(int i=0;i<5;i++)
{
out.println("Welcome to Sydney city, Aus");
}
}
catch(Exception e)
{
out.println("Thread Interrupted...");
}
}
}
// creating chennai thread
class Chennai extends Thread
{
// running state: contains the logic of thread
public void run()
{
// call the thread properties: get name of the thread
MultiThreads.Tname();
try
{
for(int i=0;i<5;i++)
24
| 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 |

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 THREAD
slm.start(); // start Salem thread
che.start(); // start Chennai thread
syd.start(); // start Sydney thread
}
}

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 |

IV. EXAMPLE OF MULTITHREADING


(ASYNCHRONOUS WAY)
1. SOURCE CODE
package multithreading;
import static java.lang.System.*;
// creating salem thread
class Salem extends Thread
{
// RUNNING STATE: EXECUTING THREAD LOGIC
public void run()
{
// print the thread name details
MultiThreads.Tname();
try
{
for(int i=0;i<5;i++)
{
// blocked state: block a thread till 500 milliseconds
Thread.sleep(500);
out.println("Welcome to Salem city, Inida");
}
}
catch(Exception e)
{
out.println("Thread Interrupted...");
}
}
}

28
| Java Threads |

// creating sydney thread


class Sydney extends Thread
{
// RUNNING STATE: EXECUTING THREAD LOGIC
public void run()
{
// print the thread name details
MultiThreads.Tname();
try
{
for(int i=0;i<5;i++)
{
// blocked state: block a thread till 1000 milliseconds
Thread.sleep(1000);
out.println("Welcome to Sydney city, Aus");
}
}
catch(Exception e)
{
out.println("Thread Interrupted...");
}
}
}
// creating chennai thread
class Chennai extends Thread
{
// RUNNING STATE: EXECUTING THREAD LOGIC
public void run()
{
29
| 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 |

V. MULTITHREADING WITH ASYNCHRONOUS MODE


(TRADITIONAL APPROACH)
1. SOURCE CODE
package join;
// extends super class Thread
class One extends Thread
{
// RUNNING STATE
public void run()
{
try
{
for(int i=0;i<5;i++)
{
// blocked state : block a thread till 400 ms
Thread.sleep(400);
System.out.println("Executing 1st thread...");
}
}
catch(Exception e)
{
System.out.println("Thread Interrupted...");
}
}
}
class Second extends Thread
{
// RUNNING STATE
public void run()
34
| 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 |

VI. MULTITHREADING WITH ASYNCHRONOUS MODE


(USING JOIN METHOD)
1. SOURCE CODE
package join;
// sub thread 1
class JOne extends Thread
{
// running state
public void run()
{
try
{
for(int i=0;i<5;i++)
{
// blocked state: block a thread till 400 ms
Thread.sleep(400);
System.out.println("Executing 1st thread...");
}
}
catch(Exception e)
{
System.out.println("Thread Interrupted...");
}
}
}
// sub thread 2
class JSecond extends Thread
{
// running state
37
| Java Threads |

public void run()


{
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 Join_MT
{
// main thread
public static void main(String[] args)throws Exception
{

System.out.println("=======================================");
System.out.println("\tMultiThreading with join method ");

System.out.println("=======================================");
// newborn states

38
| Java Threads |

JOne t1=new JOne();


JSecond t2=new JSecond();
// runnable state
t1.start();
// join the main thread and 2nd thread with1st thread
// here main and 2nd thread should wait, until the 1st thread finishes its
execution, before starting the 2nd thread and main thread
t1.join();
System.out.println("------------ End of the 1st thread ----------------");
// runnable state
t2.start();
// join the main thread and 1st thread with 2nd thread
// here main thread and 1st thread should wait, until the 2nd thread
finishes its execution
t2.join(); // join the t2 thread with main thread
System.out.println("------------ End of the 2nd thread ----------------");
}
}

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.

VII. MULTITHREADING WITH THREAD PRIORITY


1. SOURCE CODE
package multithreading;
import static java.lang.System.*;
// creating Podhigai thread (sub thread 1)
class Podhigai extends Thread
{
// RUNNING STATE
public void run()
{
for(int i=0;i<3;i++)
out.println("Podhigai superfast express is running...");
}
}
// creating Rameswaram thread (sub thread 2)
class Rameswaram extends Thread
{

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 |

Podhigai pg=new Podhigai();


// set the new name for the thread using setName() method
pc.setName("Perlcity");
ram.setName("Rameswaram");
pg.setName("Podhigai");
// set the thread prioities
ram.setPriority(Thread.NORM_PRIORITY); // default priority
pg.setPriority(Thread.MAX_PRIORITY); // setting max priority
pc.setPriority(Thread.MIN_PRIORITY); // setting min priority
// RUNNABLE STATE : READY TO EXECUTE THE THREAD
pc.start(); // start perlcity superfast
ram.start(); // start sethu express
pg.start(); // start podhigai superfast
}
}

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 |

PROBLEM IN ACCESSING SHARED DATA


UNEXPECTED OUTPUT
• We can get unexpected result, when three threads like t1, t2, t3 will
access shared data / method (Get unexpected result, when multiple
threads are accessing shared data)
CASE 1

CASE 2

47
| Java Threads |

CASE 3

48
| Java Threads |

VIII. MULTITHREADING WITH SYNCHRONIZATION


(JBank.java)
1. SOURCE CODE
public class JBank extends Thread
{
static int amt=5000;
// RUNNING STATE
public void run()
{
deposit(500);
}
// synchronized method: (only one thread will be allowed at a time)
public synchronized void deposit(int money)
{

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

You might also like