1.线程安全: 多个线程调用同一个实例的方法或变量时,是线程安全的。
HashTable里的put()方法是有synchronized关键字,所以是安全的。
HashTable ht = new Hashtable();
new Thread(()->{
ht.put("test","1")
}).start();
new Thread(()->{
ht.put("test1","1")
}).start();
2.HashTable,String,StringBuffer,Random,Vector, concurrent 是线程安全的。单个方法使用是线程安全的,但是其组合不一定是线程安全的
HashTable ht=new HashTable();
if(ht.get("key")==null) {
ht.put("key","value");
}
//thread1: get==null
//thread2: get==null
//thread1: put()
//thread2: put() 这时thread2 put()的值会覆盖thread1的值。
//因此线程安全的类的方法组合不一定线程安全,需要给予控制
3.成员变量一般是不安全的。局部变量一般是安全的。
4.注意方法的重写导致线程不安全,可以将方法或类设置为private或者final增强安全性,使其不被暴漏出去。 故谨防“外星方法”--抽象方法
5.String里的split,substring都是拷贝了一个新副本存储新的值,并不是对原有的值进行改变。为不可变类线程安全--因为其内部方法都不可改变。