【问题标题】:A thread that runs without stopping不间断运行的线程
【发布时间】:2019-11-29 08:57:41
【问题描述】:

是否可以在 java 中创建一个始终在后台工作的线程?问题是应用程序实例有时会因 OutOfMemoryException 而崩溃。因此,多个实例是并行启动的。每个实例都做一些工作:它应用户的请求将某些内容保存到数据库中。应该持续工作的流将查看数据库并以某种方式处理其中的信息。

很可能,调度器不会工作,因为线程必须不断运行并等待信号开始工作。

【问题讨论】:

  • instance sometimes crashes with an OutOfMemoryException. Therefore, several instances are launched in parallel 这是一个相当不错的解决方案
  • @CoderinoJavarino 是的,我知道。但不幸的是,我不是团队负责人,我无法影响

标签: java multithreading concurrency daemon


【解决方案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 为您提供示例。

【讨论】:

    【解决方案2】:

    你基本上需要一个无限运行的线程,并带有一些控制。

    我发现这个答案是最简单的,它可以满足您的需求。 https://stackoverflow.com/a/2854890/11226302

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-22
      • 1970-01-01
      • 2014-09-11
      • 2014-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-22
      相关资源
      最近更新 更多