我正在阅读《Java 并发实践》并查看第 51 页的示例代码。
根据该书,这段代码如果没有正确发布,就有失败的风险。因为我喜欢编写示例代码并分解它们以证明它们是如何工作的。我尝试让它抛出 AssertionError 但失败了。 (引导我走向我的上一个问题 https://stackoverflow.com/questions/2614066/java-concurrency-in-practice-sample-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,请删除睡眠)。这种竞争条件可能很少见,或者在您的特定机器上不存在 - 但至少尝试通过尝试数百万次来在一百万个案例中引发这些竞争条件。
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++);
}
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)