线程安全-同步容器

线程安全-同步容器_第1张图片
container.png

同步容器不一定是线程安全的

比如

package io.haitaoc.concurrency.example.syncContainer;



import io.haitaoc.concurrency.annotation.NotThreadSafe;

import java.util.Vector;

@NotThreadSafe
public class VectorExample2 {

    private static Vector vector = new Vector<>();

    public static void main(String[] args) {

        while (true) {

            for (int i = 0; i < 10; i++) {
                vector.add(i);
            }

            Thread thread1 = new Thread() {
                public void run() {
                    for (int i = 0; i < vector.size(); i++) {
                        vector.remove(i);
                    }
                }
            };

            Thread thread2 = new Thread() {
                public void run() {
                    for (int i = 0; i < vector.size(); i++) {
                        vector.get(i);
                    }
                }
            };
            thread1.start();
            thread2.start();
        }
    }
}

removeget操作顺序不同导致错误,需要在调用端进行额外线程同步处理才能使其安全

你可能感兴趣的:(线程安全-同步容器)