Data Science. Angular 7. Machine Learning. Data Structures. Operating System. Computer Network. Compiler Design. Computer Organization. Discrete Mathematics. Ethical Hacking. Computer Graphics. Software Engineering. Web Technology. Cyber Security. C Programming. For example, if multiple threads try to write within a same file then they may corrupt the data because one of the threads can override data or while one thread is opening the same file at the same time another thread might be closing the same file.
So there is a need to synchronize the action of multiple threads and make sure that only one thread can access the resource at a given point in time.
This is implemented using a concept called monitors. Each object in Java is associated with a monitor, which a thread can lock or unlock. Only one thread at a time may hold a lock on a monitor. Java programming language provides a very handy way of creating threads and synchronizing their task by using synchronized blocks.
You keep shared resources within this block. Here, the objectidentifier is a reference to an object whose lock associates with the monitor that the synchronized statement represents.
Now we are going to see two examples, where we will print a counter using two different threads. Is my approach is correct? My guess is that both threads trying to write to write to the console and thread T1 simply did not get a chance to write it on the second line. You've done nothing to synchronize your run method, so the printlns before and after the withdrawal and the withdrawal itself are not atomic. You're getting thread interleaving.
Could not be exactly executed in that order, but you get the idea. To make it work like you want use synchronized block. Stack Overflow for Teams — Collaborate and share knowledge with a private group.
Create a free Team What is Teams? Collectives on Stack Overflow. Learn more. Implementing bank account in Java Ask Question. Asked 10 years, 8 months ago. Active 10 years, 8 months ago. Viewed 8k times.
Balance before T2 withdrawl: Balance after T2 withdrawl: Balance before T1 withdrawl: Balance after T1 withdrawl: Balance before T2 withdrawl: Balance after T2 withdrawl: Balance before T1 withdrawl: Balance after T1 withdrawl: My question is why the line 3 Balance before T1 withdrawl: in the output gives instead of Saurabh Gokhale Add a comment. Active Oldest Votes. CPerkins CPerkins 8, 3 3 gold badges 32 32 silver badges 46 46 bronze badges. You have synchronized the account everything works correctly there , but if you want the output also in a "nice" order, then you have to synchronize it as-well.
0コメント