Java 在后台线程中运行处理程序消息

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18694732/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 10:16:17  来源:igfitidea点击:

Run Handler messages in a background thread

javaandroidmultithreadinghandler

提问by Yaroslav Mytkalyk

I want to run some Runnable in a background thread. I want to use Handler because it's convenient for delays. What I mean is

我想在后台线程中运行一些 Runnable。我想使用 Handler 因为它方便延迟。我的意思是

handler.post(runnable, delay);

Where runnableshould be run in backgroundThread. Is it possible to create such Handler? Is there a "background" Looper somewhere or how can I create it?

可运行应当运行后台线程。是否可以创建这样的处理程序?某处是否有“背景” Looper 或如何创建它?

P.S. I know how to do it with a custom class extends Thread but it requires a little more coding effort than doing it the handler way. So please don't post other solutions or something like

PS 我知道如何使用自定义类扩展 Thread 来做到这一点,但与以处理程序的方式进行相比,它需要更多的编码工作。所以请不要发布其他解决方案或类似的东西

handler.post(new Runnable() {
    @Override
    public void run() {
        new Thread() {
            @Override
            public void run() {
                //action
            }
        }.start();
    }
});

I just wander if Handler can do it the "clean" way.

如果 Handler 能以“干净”的方式做到这一点,我只是在徘徊。

采纳答案by Himanshu Khandelwal

You can simply do this:

你可以简单地这样做:

private Handler mHandler;

private HandlerThread mHandlerThread;

public void startHandlerThread(){
    mHandlerThread = new HandlerThread("HandlerThread");
    mHandlerThread.start();
    mHandler = new Handler(mHandlerThread.getLooper());
}

Then invoke with:

然后调用:

mHandler.postDelayed(new Runnable() {
        @Override
        public void run() {
          // Your task goes here
        }
    },1000);

回答by OldCurmudgeon

Not clear what you mean by Handler.

不清楚你的意思Handler

It sounds like you need a thread that is fed processes to perform by a queue. You would probably benefit from investigating Executors herebut here's a simple two-thread pair that communicate through a queue.

听起来您需要一个线程,该线程由队列执行。您可能会从这里调查Executors 中受益,但这里有一个简单的双线程对,它们通过队列进行通信。

public class TwoThreads {
  public static void main(String args[]) throws InterruptedException {
    System.out.println("TwoThreads:Test");
    new TwoThreads().test();
  }
  // The end of the list.
  private static final Integer End = -1;

  static class Producer implements Runnable {
    final Queue<Integer> queue;

    public Producer(Queue<Integer> queue) {
      this.queue = queue;
    }

    @Override
    public void run() {
      try {
        for (int i = 0; i < 1000; i++) {
          queue.add(i);
          Thread.sleep(1);
        }
        // Finish the queue.
        queue.add(End);
      } catch (InterruptedException ex) {
        // Just exit.
      }
    }
  }

  static class Consumer implements Runnable {
    final Queue<Integer> queue;

    public Consumer(Queue<Integer> queue) {
      this.queue = queue;
    }

    @Override
    public void run() {
      boolean ended = false;
      while (!ended) {
        Integer i = queue.poll();
        if (i != null) {
          ended = i == End;
          System.out.println(i);
        }
      }
    }
  }

  public void test() throws InterruptedException {
    Queue<Integer> queue = new LinkedBlockingQueue<>();
    Thread pt = new Thread(new Producer(queue));
    Thread ct = new Thread(new Consumer(queue));
    // Start it all going.
    pt.start();
    ct.start();
    // Wait for it to finish.
    pt.join();
    ct.join();
  }
}

回答by Yuichi Araki

You can set up a Looper in a background thread using Looper.prepare()and Looper.loop.

您可以使用Looper.prepare()和在后台线程中设置 Looper Looper.loop

回答by Ayman Mahgoub

You can try something like this

你可以试试这样的

    private void createHandler() {
        Thread thread = new Thread() {
            public void run() {
                Looper.prepare();

                final Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                       // Do Work
                        handler.removeCallbacks(this);
                        Looper.myLooper().quit();
                   }
                }, 2000);

                Looper.loop();
            }
        };
        thread.start();
    }