gpt4 book ai didi

Java 与 Groovy 继承和基于父类的线程上下文

转载 作者:行者123 更新时间:2023-12-01 09:03:29 25 4
gpt4 key购买 nike

我正在使用 Groovy 2.4.7,并且遇到了意外的行为。让我们看一下这个简单的 Java 代码:

public class InheritanceBugTest {

private class Parent {

private volatile String h = "Hello world";
private volatile String c;

String getHello() throws InterruptedException {
Thread t = new Thread(new Runnable() {
public void run() {
c = h;
}
});
t.start();
t.join();
return c;
}
}

private class Child extends Parent {

String getParentHello() throws InterruptedException {
return getHello();
}
}

public InheritanceBugTest() throws InterruptedException {
Parent parent = new Parent();
assert "Hello world".equals(parent.getHello());

Child child = new Child();
assert "Hello world".equals(child.getParentHello());
}

public static void main(String[] args) throws InterruptedException {

new InheritanceBugTest();

}
}

这显然在 Java 中工作得很好。现在介绍 Groovy:

class InheritanceBugTest extends Specification {

private class Parent {

private volatile String h = "Hello world";
private volatile String c;

String getHello() throws InterruptedException {
Thread t = new Thread(new Runnable() {
public void run() {
c = h;
}
});
t.start();
t.join();
return c;
}
}

private class Child extends Parent {

String getParentHello() throws InterruptedException {
return getHello();
}
}

def 'test correct Parent behavior'() {

given:
def parent = new Parent()
def hello

when:
hello = parent.getHello()

then:
hello == 'Hello world'
}

def 'test correct Child behavior'() {

given:
def child = new Child()
def hello

when:
hello = child.getParentHello()

then:
hello == 'Hello world'
}
}

在这里,我最终第一个测试运行良好,第二个测试在 Exception in thread "Thread-2" groovy.lang.MissingPropertyException: No such property: h for class: org.codehaus.groovy.InheritanceBugTest 上失败。 .

看来 Groovy 线程在不同的上下文中运行,其中没有 h存在。这种行为正常还是错误?

最佳答案

看起来它已经打开了groovy bug https://issues.apache.org/jira/browse/GROOVY-5438 .

您可以通过将访问修饰符更改为“ protected ”来避免这种情况。

关于Java 与 Groovy 继承和基于父类的线程上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41481884/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com