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

时间:2017-01-03 14:57:53

标签: java android multithreading

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

 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()概念并加入,这些都没有按预期的那样帮助。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:0)

您可以使用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();
            }
        }
    }