gpt4 book ai didi

java - 单例和线程不能一起工作

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

我有一个单例类,它也是可运行的(和可观察的)。当我尝试从主线程启动线程时,它不会创建新线程并卡在主循环中。

public class A extends Observable implements Runnable
{
private static A instance = null;

private A() {
}

public static A getInstance() {
if(instance == null) {
instance = new A();
}
return instance;
}


@Override
public void run()
{

while (true) {

System.out.print("\nSleeping");
// sleep
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.print("\n[Error]");
}
}
}

}

和主类:

Thread thread = new Thread(A.getInstance());
thread.run();
System.out.print("\nAfter...");

我看不到“After”日志,只能看到循环中的“Sleeping”。为什么?

最佳答案

您正在调用 run(),而不是 start()。

关于java - 单例和线程不能一起工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26330111/

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