我从以前的开发人员那里继承了这段代码(笑)。我正在考虑更改此设置以支持连接,而不是使用监听器类型的回调。
我的要求: 1. 我需要让调用线程等待,直到 DoMath 类线程完成。 2.我需要阻止其他线程调用它。
这个,在另一个线程(和类)中 - :
DoMath.getInstance().performMathCalc();
当它调用这个时,它当然不会等待或 hibernate :
public class DoMath {
protected math calc() {
}
public static DoMath getInstance() {
if(_instance == null) {
_instance = new DoMath();
}
return _instance;
}
// perform a synchronous math calc, and return a boolean indicating success or failure.
public boolean performMathCalc() {
MathEngine.setApplicationMode(MathEngine.AUTO);
MathEngine.getInstance().StartMathCalc(MathEngine.DIVISION);
return true;
}
// perform an async math calc, and call back the listener when done
public void performMathCalc(final listener client) {
Thread mathThread = new Thread(new Runnable() {
public void run() {
boolean result = performMathCalc();
client.mathFinished(result);
}
});
mathThread.setDaemon(true);
mathThread.start();
}
public static interface listener {
public void mathFinished(boolean success);
}
protected static DoMath _instance;
}
那么,仅使用监听器或在调用类中实现联接更好吗?
最佳答案
请注意:
public static DoMath getInstance() {
if(_instance == null) {
_instance = new DoMath();
}
return _instance;
}
不是线程安全的。为了确保您的类确实是 Singleton(相对于其 ClassLoader),您必须同步该方法或在其声明中初始化 _instance
成员。无论哪种方式,_instance
都必须是 private
或 final
或两者。
至于您的实际需求,
(1) 看来您想要将异步调用更改为同步调用,或者在其周围放置一个同步包装器。您可以通过现有的监听器接口(interface)执行后者,这将保留执行异步作业的能力。如果您不希望这样做,则不必加入,而是完全跳过启动新线程:只需在当前线程中运行计算即可。
(2) 如何防止多个线程同时运行计算部分取决于您如何解决问题 (1)。如果您使所有内容同步,那么您只需将 DoMath.performMathCalc() 设为同步方法即可。如果您保留异步计算选项,那么您可以考虑打包 java.util.concurrent.locks 来获取可以帮助您的类。
关于java - 带监听器的单例与连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26408115/