在写一些java文章时,我试图在多线程环境中不同步的对象构造的情况下重现重新排序。当构造一个重对象时没有同步/易失性/finals 并且其他线程在构造函数调用后立即访问它的情况。这是我尝试的代码:
public class ReorderingTest {
static SomeObject<JPanel>[] sharedArray = new SomeObject[100];
public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
String name = "watcher" + i;
new Thread(new Watcher(name)).start();
System.out.printf("watcher %s started!%n", name);
}
}
static class Watcher implements Runnable {
private String name;
Watcher(String name) {
this.name = name;
}
public void run() {
while (true) {
int randomIndex = (int) (Math.random() * sharedArray.length);
SomeObject<JPanel> item = sharedArray[randomIndex];
if (item == null) {
//System.out.printf("sharedArray[%s]=null%n", randomIndex);
double r = 1 + Math.random() * 1000;
sharedArray[randomIndex] = new SomeObject<JPanel>(
new JPanel(), UUID.randomUUID().toString(), r, (float)r * 33, (long)r);
} else {
//System.out.printf("sharedArray[%s]=<obj>!%n", randomIndex);
if (item.value == null ||
(item.stringField == null) ||
(item.doubleField == 0) ||
(item.floatField == 0) ||
(item.longField == 0)
) {
System.err.printf("watcher %s sees default values: %s!%n", name, item);
} else {
// fully initialized! run new construction process
double r = 1 + Math.random() * 1000;
sharedArray[randomIndex] = new SomeObject<JPanel>(
new JPanel(), UUID.randomUUID().toString(), r, (float)r * 37, (long)r);
}
}
/*try {
TimeUnit.NANOSECONDS.sleep(randomIndex);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}*/
}
}
}
static class SomeObject<V> {
V value;
String stringField;
double doubleField;
float floatField;
long longField;
SomeObject(V value, String stringField, double doubleField, float floatField, long longField) {
this.value = value;
this.stringField = stringField;
this.doubleField = doubleField;
this.floatField = floatField;
this.longField = longField;
}
@Override
public String toString() {
return "SomeObject{" +
"value=" + value == null ? "null" : "<obj>" +
", stringField='" + stringField + '\'' +
", doubleField=" + doubleField +
", floatField=" + floatField +
", longField=" + longField +
'}';
}
}
}
- 但到目前为止没有效果,我已经在不同的 2,4 和 8 核 Intel/AMD PC 上尝试了 Windows,运行了几个小时的测试 - 没有重新排序效果 - System.err.printf("watcher %s see .. .") - 未调用,静态 sharedArray[randomIndex] 引用始终包含完全构造的值。
怎么了?如何重现这个?