下面的例子是jdk文档中的。
http://java.sun.com/j2se/1.5.0/docs/api/java/lang/ThreadLocal.html
[code="java"]
public class SerialNum {
// The next serial number to be assigned
private static int nextSerialNum = 0;
private static ThreadLocal serialNum = new ThreadLocal() {
protected synchronized Object initialValue() {
return new Integer(nextSerialNum++);
}
};
public static int get() {
return ((Integer) (serialNum.get())).intValue();
}
}
[/code]
请问已经是ThreadLocal了,initialValue 这个方法 为何还需要 synchronized ?
synchronized不可以省略,initialValue是赋初值时使用的,为了保证nextSerialNumber不冲突,所以加synchronized。1.6的示例不使用是因为nextSerialNumber被声明为AtomicInteger,这个的操作本身是原子性的,所以可以不加,如果是单纯的int还是需要加。
可以不写。它的意思是使用同步机制而不是创建副本。很简单,是你想太多了 :o :o
synchronized 是多余的,而且还服务器浪费资源
你给的链接是jdk1.2的文档,已经很老了,看新的1.6的文档:
http://doc.javanb.com/java-platform-standard-edition-api-1-6-zh/java/lang/ThreadLocal.htmgz
1.2加可能是写文档的疏忽,也可能真的有特殊原因,但是1.6的文档中,上面的例子已经没有加synchronized了。
而且ThreadLocal的实现也已经变了,现在已经可以支持泛型。