我对线程安全的理解

Wiki的解释如下

Thread safety is a computer programming concept applicable to multi-threaded code. 
Thread-safe code only manipulates shared data structures in a manner that ensures that all threads behave properly
and fulfil their design specifications without unintended interaction.
There are various strategies for making thread-safe data structures

关键词就在这几个加粗的字体,是针对多线程的场合的共享数据,为了防止出现不确定的结果(多次执行结果的不确定性)。

举例:下面代码如果不加synchronized的话如果两个线程通知去i++,有可能就会出现覆盖的情况,而不是另一个线程去等待第一个完成后再去 i++

class Counter {
    private static int i = 0;

    public synchronized void inc() {
        i++;
    }
}

至于HashTable是线程安全,而HashMap不是。StringBuffer是线程安全的,而StringBuilder不是。无非也是这个道理,自我实现线程安全也就是保证同一时间只有一个线程来访问我,这样就会避免覆盖的情况。如果阅读过StringBuffer的同学都会发现,它的所有方法前面都加了synchronized,如此而已。

当然,除了用这样的方法避免之外,另外的思路就是避免线程共享变量,比如使用每次class都新重新构造,使用局部变量,只允许初始化一次

---栖息之鹰(一个外表懒洋洋的内心有激情的程序员) 此博客为笔者原著,转载时请注明出处,谢谢!
原文地址:https://www.cnblogs.com/roostinghawk/p/7422793.html