Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
7 views

Synchronization

Synchronisation concept of java

Uploaded by

Deepa Deepa
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Synchronization

Synchronisation concept of java

Uploaded by

Deepa Deepa
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

In Java, thread priority determines the relative priority of threads during

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.

Setting Thread Priority:


You can set a thread's priority using the setPriority(int priority) method.

class PriorityDemo extends Thread {


public PriorityDemo(String name) {
super(name); // Set the thread name
}

@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();
}
}
}

public static void main(String[] args) {


// Create threads
PriorityDemo t1 = new PriorityDemo("Low Priority Thread");
PriorityDemo t2 = new PriorityDemo("Normal Priority Thread");
PriorityDemo t3 = new PriorityDemo("High Priority Thread");

// 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();
}
}

n Java, thread synchronization is a mechanism to control the access of


multiple threads to shared resources. Synchronization prevents thread
interference and consistency issues caused by concurrent modifications of
shared data.

Key Concepts of Synchronization:


1. Critical Section:
 A block of code where shared resources are accessed.
 Only one thread should execute this block at a time to avoid data
inconsistency.
2. Synchronized Keyword:
 It can be used to synchronize methods or blocks of code.
 The thread that acquires the lock of the object can execute synchronized
code, while others must wait.
3. Monitor (Lock):
 Every object in Java has a monitor (or intrinsic lock).
 The synchronized keyword uses this lock to control thread access.

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.

Example: Without Synchronization

class Counter {
private int count = 0;

public void increment() {


count++; // Critical section
}

public int getCount() {


return count;
}
}

public class WithoutSynchronization {


public static void main(String[] args) throws InterruptedException {
Counter counter = new Counter();
// Create threads
Thread t1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
});

Thread t2 = new Thread(() -> {


for (int i = 0; i < 1000; i++) {
counter.increment();
}
});

t1.start();
t2.start();

t1.join();
t2.join();

// Expected 2000, but actual may be less due to thread interference


System.out.println("Final Count: " + counter.getCount());
}
}

Final Count: 1974 (example; varies per run)

Example: With Synchronization

class Counter {
private int count = 0;

// Synchronized method to increment


public synchronized void increment() {
count++; // Critical section
}
public int getCount() {
return count;
}
}

public class WithSynchronization {


public static void main(String[] args) throws InterruptedException {
Counter counter = new Counter();

// Create threads
Thread t1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
});

Thread t2 = new Thread(() -> {


for (int i = 0; i < 1000; i++) {
counter.increment();
}
});

t1.start();
t2.start();

t1.join();
t2.join();

// Correct count: 2000


System.out.println("Final Count: " + counter.getCount());
}
}

class Counter {
private int count = 0;
public void increment() {
synchronized (this) { // Synchronized block
count++;
}
}

public int getCount() {


return count;
}
}

You might also like