What is relationship between between static storage and multiple threads?
- Static member store in the method area or in other words, static member stored in main thread.
So other thread want to get the static data will go to the main thread and method area to get the data.
–> static member is share among all the threads so it’s not thread-safe(multiple thread can change static value at the same time)
We can use synchoronization mechanisms to protect the static member.Example
public class SynchronizedCounter {
// Static member variable
private static int counter = 0;// Synchronized method to increment the counter
public static synchronized void incrementCounter() {
counter++;
}// Synchronized method to get the value of the counter
public static synchronized int getCounter() {
return counter;
}public static void main(String[] args) {
// Create multiple threads that increment the counter
Thread thread1 = new Thread(new CounterIncrementer());
Thread thread2 = new Thread(new CounterIncrementer());
Thread thread3 = new Thread(new CounterIncrementer());thread1.start();
thread2.start();
thread3.start();try {
// Wait for threads to finish
thread1.join();
thread2.join();
thread3.join();
} catch (InterruptedException e) {
e.printStackTrace();
}// Print the final value of the counter
System.out.println(“Final counter value: ” + getCounter());
}
}class CounterIncrementer implements Runnable {
@Override
public void run() {
// Increment the counter 1000 times
for (int i = 0; i < 1000; i++) {
SynchronizedCounter.incrementCounter();
}
}
}