As threads are executing concurrently and they are using shared resources, multiple threads may want to access the same resources simultaneously. This scenario may create thread interference and memory inconsistency. To prevent these errors, synchronization is used.
There are two ways to deal with this problem: synchronized methods and synchronized blocks.
Method Level Synchronization
In method-level synchronization, when one thread is executing the synchronized method, other threads will not get access to the method. At a time only one thread can execute a synchronized method.
Counter.java
CountingThreadSynchMethod.java
Block Level Synchronization
In block-level synchronization, when one thread is executing a synchronized block, other threads will not be able to enter the block. At a time only one thread can execute a synchronized block.
CountingThreadSynchBlock.java
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.