从内存一致性属性中,我们知道:“在将对象放入任何并发集合之前,线程中的操作发生在另一个线程中从集合中访问或删除该元素之后的操作。”
这是否意味着:如果我在一个线程中创建一个对象并将其放入 ConcurrentLinkedQueue 中,另一个线程将看到该对象的所有属性,而无需对该对象进行其他同步?
例如:
public class Complex{
int index;
String name;
public Complex(int index, String name){
this.index = index;
this.name = name;
}
public String getName(){
return name;
}
public int getIndex(){
return index;
}
}
public class SharedQueue{
public static ConcurrentLinkedQueue queue = new ConcurrentLinkedQueue();
}
在一个线程中:
............
Complex complex = new Complex(12, "Sam");
SharedQueue.queue.add(complex);
............
在另一个线程中
......
Complex complex = SharedQueue.queue.poll();
System.out.printly(complex.getIndex() + ";" + complex.getName());
......
第二个线程肯定会看到complex
对象的属性吗?如果第二个线程恰好在第一个线程将对象放入队列后获取对象并打印它。
我们知道,在正常情况下,如果对象是共享的,我们应该在多线程环境中同步对象。
喜欢
public class Complex{
int index;
String name;
public Complex(int index, String name){
this.index = index;
this.name = name;
}
public synchronized String getName(){
return name;
}
public synchronized int getIndex(){
return index;
}
}