[英]Java concurrency -_- visibility/reordering when sharing vars between threads
我正在迈出学习多线程的第一步,并构建了一些测试程序,以便为自己创建一些见识。 由于重新排序的可能性,我不确定我的解决方案是安全的。
这是主程序:
public class SynchTest {
private static Sychint i = new Sychint();
private static SychBool b = new SychBool();
public static void main(String[] args) {
System.err.println("begin");
b.setB(false);
i.seti(100);
// create 100 dra threads
for (int i = 0; i < 1000; i++) {
new dra().start();
}
// should these lines be synched as well in case of reordering? If so, how to?
i.seti(200);
b.setB(true);
}
private static class dra extends Thread {
@Override
public void run() {
// wait for main thread to set b = true
while (!b.getB()) {
dra.yield();
}
// i should always be 200 in case of correct synchronisation
if (i.geti() != 200) {
System.err.println("oh noes! " + i.geti());
} else {
// System.out.println("synch working!");
}
}
}
}
这些是Sychint的类:
public class Sychint {
private int i = 0;
public synchronized void seti(int i){
this.i = i;
}
public synchronized int geti (){
return this.i;
}
}
SychBool:
public class SychBool {
private boolean b;
public synchronized boolean getB() {
return b;
}
public synchronized void setB(boolean b) {
this.b = b;
}
}
任何建议/保证将非常有帮助!
谢谢
多线程的新手:)
// should these lines be synched as well in case of reordering? If so, how to?
i.seti(200);
b.setB(true);
在这种情况下,你很好。
b.setB(true)
不能在i.seti(200)
之上重新排序。 无法在MonitorExit上方订购NormalStore和MonitorEnter。 在您的情况下,监视器退出发生在seti
的末尾,接着是监视器进入和( setB
)正常存储,因此此处无法重新排序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.