42

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

handler.post(runnable, delay);

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

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

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

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

4

5 回答 5

80

你可以简单地这样做:

private Handler mHandler;

private HandlerThread mHandlerThread;

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

然后调用:

mHandler.postDelayed(new Runnable() {
        @Override
        public void run() {
          // Your task goes here
        }
    },1000);
于 2015-04-01T11:31:34.053 回答
9

你可以试试这样的

    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();
    }
于 2014-12-22T09:33:48.470 回答
5

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

于 2013-09-09T09:09:23.660 回答
0

不清楚你的意思Handler

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

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();
  }
}
于 2013-09-09T09:07:12.497 回答
0

我在 kotlin 中实现了在后台线程上运行任务的简单方法:

fun background(function: () -> Unit) = handler.post(function)

private val handler: Handler by lazy { Handler(handlerThread.looper) }

private val handlerThread: HandlerThread by lazy {
    HandlerThread("RenetikBackgroundThread").apply {
        setUncaughtExceptionHandler { _, e -> later { throw RuntimeException(e) } }
        start()
    }
}

总体思路是,任务很容易执行,并且一个接一个地依次运行,未捕获的异常被传播到主线程,这样它们就不会丢失。稍后的函数基本上是在主线程上运行的处理程序。

因此,您可以像这样简单地发布任务:

 background {
    some task to do in background...  
 }

一些科德

 background {
    other task to do in background...  
    later {
        on main thread when all tasks are finished...
    }
 }
于 2020-06-13T20:17:19.467 回答