在Java中是否可以创建始终在后台运行的线程?问题在于应用程序实例有时会因OutOfMemoryException崩溃。因此,并行启动了几个实例。每个实例都做一些工作:根据用户的请求将某些内容保存到数据库中。流应该持续工作,它将查看数据库并以某种方式处理其中的信息。
由于线程必须一直运行并等待信号开始工作,所以sheduler很可能无法工作。
答案 0 :(得分:1)
首先,建议您调查并解决OutOfMemoryException,因为这样最好避免这些情况。您可以实例化一个等待请求的线程,执行一个请求,然后返回以等待另一个请求。线程的实现是这样的:
/** Squares integers. */
public class Squarer {
private final BlockingQueue<Integer> in;
private final BlockingQueue<SquareResult> out;
public Squarer(BlockingQueue<Integer> requests,
BlockingQueue<SquareResult> replies) {
this.in = requests;
this.out = replies;
}
public void start() {
new Thread(new Runnable() {
public void run() {
while (true) {
try {
// block until a request arrives
int x = in.take();
// compute the answer and send it back
int y = x * x;
out.put(new SquareResult(x, y));
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
}
}).start();
}
}
对于调用方方法:
public static void main(String[] args) {
BlockingQueue<Integer> requests = new LinkedBlockingQueue<>();
BlockingQueue<SquareResult> replies = new LinkedBlockingQueue<>();
Squarer squarer = new Squarer(requests, replies);
squarer.start();
try {
// make a request
requests.put(42);
// ... maybe do something concurrently ...
// read the reply
System.out.println(replies.take());
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
要了解更多信息,您可以开始阅读我发现的here帖子,为您提供示例。
答案 1 :(得分:1)
您基本上需要一个带有某些控件的无限运行线程。
我发现这个答案是最简单的,它可以满足您的需求。 https://stackoverflow.com/a/2854890/11226302