使用 EJB 在扩展线程上实现 Runnable
Implements Runnable over Extends Thread with EJB
假设 class MyCoolProcess
具有我的应用程序的逻辑,需要在它自己的线程中调用。我们将创建一个线程,调用它并继续应用程序。
这个 class 是一个 EJB;用 @Stateless
注释
现在我们有了 MyController
class;这将调用一个新线程。
代码:
public class MyController {
@EJB
MyCoolProcess p;
public Response foo() {
Thread t = new Thread() {
public void run() {
p.run();
}
};
t.start();
// continues ...
}
}
@Stateless
public class MyCoolProcess {
public void run() {
// heavy task
}
}
即工作正常;关键是......在我尝试使用 Runnable
界面的解决方案之前。这是我第一次想要的。方法是:
public class MyController {
@EJB
MyCoolProcess p;
public Response foo() {
Thread t = new Thread(p);
t.start();
// continues ...
}
}
@Stateless
public class MyCoolProcess implements Runnable {
@Override
public void run() {
// heavy task
}
}
那是行不通的。实际上,服务器无法启动。尝试注入依赖项时崩溃。如果我是 EJB,我将无法实现接口 Runnable
,不是吗? 为什么
还有...有什么办法可以用 Runnable
方式代替匿名 class 吗?
来自 EJB 规范:
The enterprise bean must not attempt to manage threads. The enterprise bean must not attempt to start, stop, suspend, or resume a thread, or to change a thread’s priority or name. The enterprise bean must not attempt to manage thread groups.
假设 class MyCoolProcess
具有我的应用程序的逻辑,需要在它自己的线程中调用。我们将创建一个线程,调用它并继续应用程序。
这个 class 是一个 EJB;用 @Stateless
现在我们有了 MyController
class;这将调用一个新线程。
代码:
public class MyController {
@EJB
MyCoolProcess p;
public Response foo() {
Thread t = new Thread() {
public void run() {
p.run();
}
};
t.start();
// continues ...
}
}
@Stateless
public class MyCoolProcess {
public void run() {
// heavy task
}
}
即工作正常;关键是......在我尝试使用 Runnable
界面的解决方案之前。这是我第一次想要的。方法是:
public class MyController {
@EJB
MyCoolProcess p;
public Response foo() {
Thread t = new Thread(p);
t.start();
// continues ...
}
}
@Stateless
public class MyCoolProcess implements Runnable {
@Override
public void run() {
// heavy task
}
}
那是行不通的。实际上,服务器无法启动。尝试注入依赖项时崩溃。如果我是 EJB,我将无法实现接口 Runnable
,不是吗? 为什么
还有...有什么办法可以用 Runnable
方式代替匿名 class 吗?
来自 EJB 规范:
The enterprise bean must not attempt to manage threads. The enterprise bean must not attempt to start, stop, suspend, or resume a thread, or to change a thread’s priority or name. The enterprise bean must not attempt to manage thread groups.