我正在阅读“Java 并发实践”并查看第 51 页的示例代码。
根据这本书,这段代码如果没有正确发布,就有失败的风险。因为我喜欢编写示例代码并分解它们以证明它们是如何工作的。我尝试让它抛出 AssertionError 但失败了。 (引导我到我的 previous question )
任何人都可以发布示例代码以便抛出 AssertionError 吗?规则:不要修改 Holder 类。
public class Holder{
private int n;
public Holder(int n){
this.n = n;
}
public void assertSanity(){
if (n != n) {
throw new AssertionError("This statement is false");
}
}
}
我已经修改了该类,使其更加脆弱,但我仍然无法抛出 AssertionError。
class Holder2 {
private int n;
private int n2;
public Holder2(int n) throws InterruptedException{
this.n = n;
Thread.sleep(200);
this.n2 = n;
}
public void assertSanity(){
if (n != n2) {
throw new AssertionError("This statement is false");
}
}
}
是否可以使上述任一类抛出 AssertionError?或者我们是否必须接受他们偶尔会这样做,而我们无法编写代码来证明这一点?
最佳答案
我会在多处理器计算机上运行它几个小时,看看会发生什么(如果您使用 Holder2,请删除 sleep )。这种竞争条件可能很少见,或者在您的特定机器上不存在 - 但至少尝试通过尝试数百万次来在一百万个案例中引发这些竞争条件。
class Checker {
private Holder h;
public Checker() {
h = new Holder(42);
}
public void check() {
h.assertSanity();
}
public void create(int n) {
h = new Holder(n);
}
}
public class MyThread extends thread{
private bool check;
private final Checker c;
public MyThread(bool check,Checker c) {
this.check = check;
this.c = c;
}
public static void main(String[] args) {
Checker c = new Checker();
MyThread t1 = new MyThread(false,c);
MyThread t2 = new MyThread(true,c);
t1.start();
t2.start();
t1.join();
t2.join();
}
public void run() {
int n = 0;
while(true) {
if(check)
c.check();
else
c.create(n++);
}
}
}
}
关于java - 如何围绕未正确发布的值演示竞争条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33500601/