Synchronization
Synchronization
the scheduling process. The thread scheduler uses this priority value to
decide which thread to run when multiple threads are waiting to execute.
Key Points:
1. Range of Priorities:
Java thread priorities are integers ranging from:
Thread.MIN_PRIORITY (1)
Thread.NORM_PRIORITY (5)
Thread.MAX_PRIORITY (10)
2. Default Priority:
By default, every thread is assigned Thread.NORM_PRIORITY.
3. Effect on Scheduling:
Higher-priority threads are more likely to get CPU time than lower-priority
ones. However, thread priority behavior is platform-dependent and should
not be relied upon for precise control over thread execution.
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(getName() + " with priority " + getPriority() + " is
running.");
try {
Thread.sleep(500); // Pause the thread for a while
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
// Set priorities
t1.setPriority(Thread.MIN_PRIORITY); // Priority 1
t2.setPriority(Thread.NORM_PRIORITY); // Priority 5
t3.setPriority(Thread.MAX_PRIORITY); // Priority 10
// Start threads
t1.start();
t2.start();
t3.start();
}
}
Types of Synchronization:
1. Method Synchronization:
Only one thread can execute a synchronized method of an object at a time.
2. Block Synchronization:
Synchronizes a specific block of code, reducing the scope of synchronization
and improving performance.
class Counter {
private int count = 0;
t1.start();
t2.start();
t1.join();
t2.join();
class Counter {
private int count = 0;
// Create threads
Thread t1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
});
t1.start();
t2.start();
t1.join();
t2.join();
class Counter {
private int count = 0;
public void increment() {
synchronized (this) { // Synchronized block
count++;
}
}