refer to this article , let me translate:
this is a method that is atomic:
public static void main(String[] args) {
VectorTest vectorTest = new VectorTest();
new Thread(new Runnable() {
public void run() {
vectorTest.getVector();
}
}).start();
new Thread(new Runnable() {
public void run() {
vectorTest.deleteVector();
}
}).start();
}
two threads are opened here, one executes the first method and the other executes the second method. The first method first gets the size of the vector, and then begins to sleep. While the first method is not paying attention, the second method comes in and deletes the last element in the vector. When the first method wakes up and wants to find the last element, it throws an error. So the composite operation is not atomic and is interrupted by insertion.
the solution is to add a lock:
public int getVector(){
synchronized (vector) {
int index = vector.size() - 1;
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return vector.get(index);
}
}
synchronized
means Synchronize. Synchronize means that this step cannot be finished, and the next step cannot be started, so this ensures that the whole operation is still atomic, and there is no possibility of being inserted.
Previous: How does Yii achieve third-party authorization and jump to the previous page?
Next: Is there any difference between git clone xxx and git clone xxx.git?