0

我正在迈出学习多线程的第一步,并构建了一个小测试程序,以便为自己创造一些见解。由于重新排序的可能性,我不相信我的解决方案是安全的。

这是主程序:

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;
    }


}

任何建议/保证都会非常有帮助!

谢谢,

多线程新手:)

4

1 回答 1

1
// 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)。NormalStore 和 MonitorEnter 不能在 MonitorExit 之上排序。在您的情况下,监视器退出发生在 末尾seti,然后是监视器进入和正常存储(的setB),因此此处无法重新排序。

于 2013-09-04T14:17:27.450 回答