3

为了这个问题,我正在使用AsyncTask并且只是切换到使用传统的原因不值得讨论。Thread

我可以做些什么来在线程启动之前和之后执行某些操作,类似于 onPre/PostExecute 的功能?

例如,假设我想在线程开始之前显示一个加载圆圈,并在它结束时将其关闭。我该怎么做?

对于执行后位,我正在使用 thread.join() ,它似乎可以解决问题。我不确定这是否是解决方法,或者如何在执行前做一些事情。

4

2 回答 2

4

我可以做些什么来在线程启动之前和之后执行某些操作,类似于 onPre/PostExecute 的功能?

onPreExecute()-> 在调用你的之前执行start()的语句Thread

onPostExecute()-> 调用runOnUiThread(), 或post()a View, 从您的Thread, 提供Runnable要在主应用程序线程上执行的a

我该怎么做?

理想情况下,你不会。进度对话框很烂。在你的 UI 中的某个地方放置一个进度指示器(例如,操作栏、标题栏),并禁用在你的线程运行时用户无法安全执行的一些操作。

话虽如此,您可能会DialogFragment在执行线程之前显示,然后在线程通过上述机制完成后删除片段。

对于执行后位,我正在使用 thread.join() ,它似乎可以解决问题。

伊克。这将阻塞你所在的任何线程,如果那是主应用程序线程,那真的很糟糕。


更新

示例runOnUiThread()

new Thread() {
  public void run() {
    // do cool stuff
    runOnUiThread(new Runnable() {
      public void run() {
        // do other cool stuff quickly on the main application thread
      }
    );
  }
}).start();
于 2012-10-15T22:13:59.117 回答
0

锁存器(例如 CountDownLatch)可能是另一种有用的方法。

public class TestHarness {
public long timeTasks(int nThreads, final Runnable task)
        throws InterruptedException {
    final CountDownLatch startGate = new CountDownLatch(1);
    final CountDownLatch endGate = new CountDownLatch(nThreads);

    for (int i = 0; i < nThreads; i++) {
        Thread t = new Thread() {
            public void run() {
                try {
                    startGate.await();
                    try {
                        task.run();
                    } finally {
                        endGate.countDown();
                    }
                } catch (InterruptedException ignored) { }
            }
        };
        t.start();
    }

    long start = System.nanoTime();
    startGate.countDown();
    endGate.await();
    long end = System.nanoTime();
    return end-start;
}

}

于 2012-10-16T06:01:27.630 回答