Multithreading Part2
Multithreading Part2
Thread Prioritization
• Each thread in Java has a priority.
• Priority is represented by a number between 1 and 10.
• Three priority constants are defined in Thread class as follows
Constant Value
NORM_PRIORITY 5
MIN_PRIORITY 1
MAX_PRIORITY 10
• In most cases, thread scheduler schedules the threads according to their priority
(known as pre-emptive scheduling). But it is not guaranteed because it depends on
JVM specification that is which scheduling it chooses.
• setPriority() method is used to set thread priority value.
• getPriority() method is used to return priority value.
Question: Run thread A B and C concurrently with different priority. Print their
corresponding name and priority also when they are running. Thread A, B and C
must sleep for 1000ms, 5000ms, 1000 ms respectively.
Output:
Signature of suspend ()
• resume() method is used to resume a thread which was suspended using suspend()
method.
• This method allows the suspended thread to start again.
Signature of suspend ()
• Both suspend() and resume() are deprecated method in Java. Hence the program shows
warning at compile time.
Thread Synchronization
Synchronization is the capability of control the access of multiple threads to any shared
resource. Synchronization is needed in case we want only one thread can access the shared
resource at a time. In other words synchronization achieves mutual exclusion among multiple
concurrent threads.
The synchronization is mainly used to
o To prevent thread interference.
o To prevent inconsistency problem.
Mutual Exclusion helps keep threads from interfering with one another while sharing data.
This can be done by the following ways in java:
1. by synchronized method
2. by synchronized block
Synchronized Method
• If synchronized keyword is used before method signature, it is known as synchronized
method.
• Synchronized method is used to lock an object for any shared resource.
• When a thread invokes a synchronized method, it automatically acquires the lock for that
object and releases it when the method returns