The capability to control the access of multiple threads to any shared resources.
Ieads to Dead lock
Use join()
Avoid nested locks.
Avoid unnecessary locks.
Why use it
To prevent RAC.E condition.
Type;s
Process Synchronization
Thread Synchronization
Mutual Exclusive
Synchronized block
To lock an object for any shared resource,
static synchronization
To make any static method , as synchronized lock will be on the class not object
Synchronized method
Used to lock an object for any shared resource
Cooperation
By extending Thread class.
Override run() and call start() to begin execution.
Some common method of thread class are given
start()
Start a thread by calling run()
getPriority()
Suspend thread for a period of time
run()
Entry point for thread
join()
Wait for thread to terminate
isALive()
Determine if thread is still running
getName()
Obtain a thread name.
By implementing Interface
Instantiate object of type thread and call start() to execute run()
Common methods of runnable interface
run()
To perform actions for a thread
Execution of multiple threads at same time.
Advantages
1. Greater CPU utilization and improved user experience
Disadvantages
May lead to deadlock and increaes code complexity and also increased memory usage.
Ther through functions which are implemeted as final and called with synchronized context
wait()
notify()
notifyAll()
Thread class provides three methods for interrupting a thread.
Interrupt()
to set the interrupt flag for a thread
isInterrupted()
To check if onterrupt flag has been set fo the thread.
interrupted()
To check if current thread is interrupted
Games
Networking
Websites
Data Processing
New
Before start() thread is in new state
Runnable
When new thread is started
Running
A thread scheduler selects the thread , it starts running.
Blocked/Waiting
When the thread is inactive for a span of time
Terminated
run() exits normally or any unusual error occurs
Time waiting
When the thread is waiting for a resource but for a given time interval.