等到无限 while 循环完成

Wait until infinite while loop is completed

我有一个在另一个线程上运行的无限 while 循环。在这个 while 循环中,我使用了一个字符串。对于这个字符串,我还有一个 setter。当有人调用 setter 时,我希望它等到 while 循环的当前迭代完成并为下一次迭代更改它。

这是我试过的:

import java.util.concurrent.TimeUnit;

public class Test {

    private String testString = "aaaaaaa";

    private Test() {
        new Thread(() -> {
            while (true) {
                synchronized (testString) {
                    System.out.println(testString);

                    // Simulating a thread blocking operation
                    try {
                        TimeUnit.SECONDS.sleep(10);
                    } catch (InterruptedException exception) {
                        exception.printStackTrace();
                    }

                    System.out.println(testString);
                }
            }
        }).start();
    }

    private void setTestString(String testString) {
        synchronized (testString) {
            this.testString = testString;
        }
    }

    public static void main(String[] args) {
        Test test = new Test();

        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException exception) {
            exception.printStackTrace();
        }

        test.setTestString("bbbbbbbb");
    }
}

预期输出:

aaaaaaa
aaaaaaa
bbbbbbbb
bbbbbbbb
bbbbbbbb
bbbbbbbb
...

实际输出:

aaaaaaa
bbbbbbbb
bbbbbbbb
bbbbbbbb
bbbbbbbb
bbbbbbbb
...

为什么 setTestString 方法没有等待?我做错了什么?

问题是您的线程每次都在读取更新的实例变量。如果你希望循环的迭代看到一个一致的值,你应该只读取一次实例变量的值。此外,由于您是从一个线程写入它并从另一个线程读取它,因此您需要使其可变或在同步方法中执行 read-write。

private volatile String testString = "aaaaaaa";

private Test() {
    new Thread(() -> {
        while (true) {
                // volatile read
                String localTestString = testString;

                System.out.println(localTestString);

                // Simulating a thread blocking operation
                try {
                    TimeUnit.SECONDS.sleep(10);
                } catch (InterruptedException exception) {
                    exception.printStackTrace();
                }

                System.out.println(localTestString);
        }
    }).start();
}

When someone calls the setter, I want it to wait until the current iteration of the while loop finished

这不是一个好的解决方案。如果让 set 方法等待,则不能保证在循环的当前迭代完成后它会被调度。大家可以自己看看:把set方法改成

private void setTestString(String testString) {
    synchronized (this.testString) {
        this.testString = testString;
    }
}