Java 循环器泄漏消息

Java 循环器泄漏消息,java,android,multithreading,memory-leaks,Java,Android,Multithreading,Memory Leaks,所以我有一个活套,我用它来执行长时间运行的任务。 我传递它Worker对象,它本质上是一个围绕可运行程序的包装器 我注意到它似乎正在泄漏大小完全相同的消息对象 你知道为什么会这样吗 线程: public class WorkerQueue extends Thread { public Handler handler; int priority = Thread.MIN_PRIORITY + 1; private static WorkerQueue self = null;

所以我有一个活套,我用它来执行长时间运行的任务。 我传递它
Worker
对象,它本质上是一个围绕可运行程序的包装器

我注意到它似乎正在泄漏大小完全相同的消息对象

你知道为什么会这样吗

线程:

public class WorkerQueue extends Thread {
  public Handler handler;
  int priority = Thread.MIN_PRIORITY + 1;
  private static WorkerQueue self = null;

  public static WorkerQueue getInstance() {
    if (self == null) {
      self = new WorkerQueue();
      self.start();
      self.setPriority(priority);
    }

    return self;
  }

  @Override
  public void run() {
      Looper.prepare();
      handler = new Handler();
      handler.getLooper().getThread().setPriority(priority);
      Looper.loop();    
  }

  public synchronized void enqueueTask(final Worker task) {
    handler.post(new Runnable() {
      @Override
      public void run() {
          task.run();
      }
    });
  }
}

根据android文档,您应该为此使用一个

您可以这样做:

ExecutorService executor = Executors.newCachedThreadPool(); //or whatever you think is best, read the Javadocs for the different options under Executors
executor.execute(new Runnable() {
    @Override
    public void run() {
        //implement long running task here
    }
});
让当前的Worker类实现Runnable应该不难,然后可以将它们直接传递给execute方法


当然,如果您愿意,您可以随时重写Java的ExecutorService(这似乎是您正在做的),但最终您的境况可能不会更好。

hmm我之所以使用活套,是因为我可以选择将任务排在队列的最前面。有没有一种方法可以通过ThreadPoolExecutor实现这一点?嗯,如果您仔细研究一下,有一种方法允许您访问队列,但是“method getQueue()允许访问工作队列以进行监视和调试。强烈反对将此方法用于任何其他目的。”cachedThreadPool的全部要点是,它会尽快开始您设置的所有任务(它不是单线程的),根据需要创建新线程或重用旧线程。ScheduledThreadPoolExecutor允许您计划任务。