A small problem with multithreading and composite operations

< H1 > Hello, everyone. When I was reading an article, the content mentioned < / H1 >. < H2 > "the atomicity of a single method does not guarantee the atomicity of compound operation " < / H2 >. < H2 > what is the meaning of the compound operation in this sentence? can you give me an example? < / H2 > < H2 > Thank you < / H2 >

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.

Menu