If more than one thread shares a common resource (file or memory block), it should be ordered so that one thread can never change the resource while the other thread is using it. If one thread modifies a record in a file, and the other thread modifies the same record at the same time, it can cause serious problems. One way to handle this situation is to use synchronization for related threads.
The purpose of synchronization is to make only one thread accessible at any given moment when multiple threads attempt to access a single resource. There are two ways to manage thread execution using synchronization.
Both the synchronization method and the synchronization block are implemented using synchronized. Synchronized can set a lock for a specific sentence block in any object. The method of use is as follows.
synchronized( theObject )
statements; // the Object is synchronized.
synchronized( theObject )
{
statements; // the Object is synchronized.
}
While the statement statement is executed, theObject cannot be used in other synchronized threads. Other synchronized threads mean threads that use synchronized or synchronized methods, as in the code above. Examples of the synchronized method are as follows.
class theObject
{
synchronized public void method()
{
statement;
}
}
© 2024 OneMinuteCode. All rights reserved.