Зміст курсу
Multithreading in Java
Multithreading in Java
Thread Synchronization
Synchronized Methods and Blocks
Synchronized methods and blocks in Java prevent multiple threads from accessing the same resource simultaneously. This helps avoid issues like data races, where multiple threads attempt to modify a shared resource at the same time.
Real-life example: Imagine a warehouse with a single entrance and exit. If multiple people try to use the same door at once, it can cause chaos. Synchronization in programming acts like a controller at the door, allowing only one person to pass through at a time to prevent collisions.
Synchronized Methods
When a method is declared with the synchronized
keyword, it automatically locks the object to which the method belongs for the duration of the method's execution.
Code example
Main
public synchronized void increment() { //Adding the synchronized count++; }
In this example, the increment()
method is synchronized, meaning only one thread can execute this method at any given time.
Synchronized Blocks
Synchronized blocks let you synchronize only a specific section of a method, which is useful if you only want to synchronize a particular part of the code.
Code example
Main
public void increment() { synchronized(this) { count++; } }
In this example, only the code inside synchronized(this)
is synchronized, which improves performance if the entire method does not need synchronization.
Note
In the
synchronized(this)
block, the keywordthis
means that the code block is synchronized on the current instance of the object, specifically on the object for which this method is called.
Object Monitors
When a thread acquires an object monitor, it gains exclusive access to synchronized methods or blocks of that object. Other threads attempting to access synchronized methods or blocks of the same object will be blocked until the monitor is released.
Methods wait(), notify(), notifyAll()
The wait()
method is used to suspend the execution of the current thread and release the resources it occupies until another thread calls the notify()
or notifyAll()
method for the same monitor object.
The notify()
and notifyAll()
methods are used to resume the execution of one or all threads blocked on a monitor object.
Note
The
wait()
,notify()
, andnotifyAll()
methods must be called inside a synchronized block associated with the same monitor object as the pending thread to ensure proper synchronization.
In the next chapter, we'll explore what can occur if you don't use synchronization.
Дякуємо за ваш відгук!