java - 如何暂停线程一段时间,然后在用户交互后显示UI,继续线程执行

标签 java android multithreading

我已经启动了线程,在该线程中我尝试连接到服务器,收到响应后,我必须使用事件监听器更新 UI(通过接口(interface)实现)。这里,收到响应后,一旦用户单击“确定”,我需要显示弹出对话框,需要继续线程并完成其他过程。

 class ConnectionThread extends Thread {
        ConnectionThread() {
            this.setName("ConnectionThread");
        }

        @Override
        public void run() {
        // Need to pause the thread for sometime, Need to do the functionality here.  
     ((Activity)mContext).runOnUiThread(new Runnable() {
                public void run() {
            // custom dialog
               showAlertDialog();  
               // start the thread functionality again from that position.  
 }
});

}

我尝试过 wait() 概念并加入,但没有达到预期的效果。任何帮助表示赞赏。

最佳答案

您可以使用countdownlatch

class ConnectionThread extends Thread {
        CountDownLatch countDownLatch = new CountDownLatch(1);
        public ConnectionThread() {
            this.setName("ConnectionThread");
        }

        @Override
        public void run() {
            try {
                sleep(2000);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //update ui then
                        countDownLatch.countDown();
                    }
                });
                countDownLatch.await();
                //start process again
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

关于java - 如何暂停线程一段时间,然后在用户交互后显示UI,继续线程执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41446285/

相关文章:

java - TrustStore 初始化失败但 KeyStore 成功

java - 字符串到列表<String>的内存高效映射

android - 如何从 Android 应用程序显示 360 度全景图

java - N次执行后协调多个线程

java - Kotlin Spek 中的组执行顺序错误

java - 在 Spring 中确定不支持的媒体类型最理想的时间/地点?

android - 如何修复错误 Could not find class 'io.realm.rx.RealmObservableFactory$2'?

android - Google Play 应用程序签名流程证书

java - 你如何在 java webdriver 中使用线程运行两个 firefox 实例

java - ExecutorService 没有关闭