Java并发性-线程间共享变量时的可见性/重新排序
我正在学习多线程的第一步,并构建了一个小测试程序,以便为自己创造一些见解。我不相信我的解决方案是安全的,因为可能会重新订购 这是主程序:Java并发性-线程间共享变量时的可见性/重新排序,java,multithreading,visibility,Java,Multithreading,Visibility,我正在学习多线程的第一步,并构建了一个小测试程序,以便为自己创造一些见解。我不相信我的解决方案是安全的,因为可能会重新订购 这是主程序: public class SynchTest { private static Sychint i = new Sychint(); private static SychBool b = new SychBool(); public static void main(String[] args) { System.
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!");
}
}
}
}
SychBool:
public class SychBool {
private boolean b;
public synchronized boolean getB() {
return b;
}
public synchronized void setB(boolean b) {
this.b = b;
}
}
任何建议/保证都会非常有用
Thnx
多线程新手:)
在这种情况下你很好
b.setB(true)
不能在i.seti(200)
上重新排序。无法在MonitorExit之上订购NormalStore和MonitorCenter。在您的情况下,监视器退出发生在seti
的末尾,然后是监视器进入和正常存储(ofsetB
),因此这里不可能进行重新排序。您到底想做什么……这是一个非常聪明的收益率用法()。使用对象监视器和wait()/notify(),现在您有了一个美化的繁忙循环。
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);