Java-17.4 synchronization (4)-synchronization blocking, synchronized, and volatile
This section describes synchronization blocking, synchronized, and volatile.
1. Synchronization Blocking
We mentioned previously that synchronized is placed on the synchronization method:
Public synchronized void transfer (int fromAccount, int toAccount, double money) {if (accounts [fromAccount] <money) {return;} accounts [fromAccount]-= money; System. out. printf ("transferred from" + fromAccount + "account % 10.2f RMB,", money); accounts [toAccount] + = money; System. out. printf ("transferred from" + toAccount + "account to % 10.2f RMB,", money); System. out. printf ("Total: % 10.2f RMB", getTotal (); System. out. println ();}
In fact, his equivalent code is as follows:
Private Object lock = new Object (); public void transfer (int fromAccount, int toAccount, double money) {synchronized (lock) {if (accounts [fromAccount] <money) {return;} accounts [fromAccount]-= money; System. out. printf ("transferred from" + fromAccount + "account % 10.2f RMB,", money); accounts [toAccount] + = money; System. out. printf ("transferred from" + toAccount + "account to % 10.2f RMB,", money); System. out. printf ("Total: % 10.2f RMB", getTotal (); System. out. println ();}}
The above lock acts as the lock we usually call. Only by holding this lock can the thread enter the method for operation, and synchronized controls this lock and can only be held by one thread at a time, to implement synchronization blocking.
2. volatile
Volatile is another method to implement thread blocking, but it has limitations: It only completes variable assignment without other operations.
Feasible Method:
package com.ray.ch17;public class Test {private volatile boolean isDone;public boolean isDone() {return isDone;}public void setDone(boolean isDone) {this.isDone = isDone;}}
Equivalent code:
package com.ray.ch17;public class Test {private boolean isDone;public synchronized boolean isDone() {return isDone;}public synchronized void setDone(boolean isDone) {this.isDone = isDone;}}
Not feasible:
package com.ray.ch17;public class Test {private volatile boolean isDone;public void flipDone() {isDone = !isDone;}}
Summary: This section describes synchronization blocking and volatile usage.