gpt4 book ai didi

java - 我可以创建多个 STATIC 嵌套对象吗?

转载 作者:太空宇宙 更新时间:2023-11-04 08:14:56 25 4
gpt4 key购买 nike

在 Java SE 7 教程的死锁部分中,有一个示例,如下所示。我不明白为什么main方法可以创建2个STATIC嵌套对象(实际上它被定义为静态嵌套类)。据说没有任何静态类的实例,对吗?谁能帮我吗?谢谢。

==================================================================================================阿尔方斯和加斯顿是 friend ,并且非常相信礼貌。严格的礼貌规则是,当你向 friend 鞠躬时,你必须保持鞠躬状态,直到你的 friend 有机会还礼。不幸的是,这条规则没有考虑到两个 friend 可能同时互相鞠躬的可能性。这个示例应用程序“死锁”模拟了这种可能性:

public class Deadlock {
static class Friend {
private final String name;
public Friend(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public synchronized void bow(Friend bower) {
System.out.format("%s: %s"
+ " has bowed to me!%n",
this.name, bower.getName());
bower.bowBack(this);
}
public synchronized void bowBack(Friend bower) {
System.out.format("%s: %s"
+ " has bowed back to me!%n",
this.name, bower.getName());
}
}

public static void main(String[] args) {
final Friend alphonse =
new Friend("Alphonse");
final Friend gaston =
new Friend("Gaston");
new Thread(new Runnable() {
public void run() { alphonse.bow(gaston); }
}).start();
new Thread(new Runnable() {
public void run() { gaston.bow(alphonse); }
}).start();
}
}

当死锁运行时,两个线程在尝试调用 BowBack 时很可能都会阻塞。两个 block 都不会结束,因为每个线程都在等待另一个线程退出弓。

最佳答案

来自 Java 教程:实际上,静态嵌套类在行为上是一个顶级类,为了打包方便而嵌套在另一个顶级类中。

您可以从 Deadlock 内部删除 Friend 并将其作为外部类,而不改变行为。

“静态”是指访问外部类中的变量和方法。与静态(类)方法一样,静态嵌套类不能直接引用其封闭类中定义的实例变量或方法 - 它只能通过对象引用使用它们。

我认为它没有在任何地方说“没有任何静态类的实例”。外部类不能是静态的,嵌套类实际上是外部类。

这个问题问得好 - 我最近浏览了这个例子,但没有考虑到这一点。

关于java - 我可以创建多个 STATIC 嵌套对象吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10594714/

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