Java singleton和thread不能一起工作
我有一个单例类,它也是可运行的(和可观察的)。当我试图从main启动线程时,它不会创建一个新线程,并且会卡在主循环中Java singleton和thread不能一起工作,java,Java,我有一个单例类,它也是可运行的(和可观察的)。当我试图从main启动线程时,它不会创建一个新线程,并且会卡在主循环中 public class A extends Observable implements Runnable { private static A instance = null; private A() { } public static A getInstance() { if(instance == null) {
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...");
我看不到“之后”日志,只是循环中的“睡眠”。为什么?您正在调用run(),而不是start()。并且。。。(如果您能解释一下,那就太好了。)区别在于,
start()
是库提供的方法,当您想要启动新线程时,可以调用它run()
是为库提供的在新线程中调用的方法。