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

uqjltbpv  于 2021-07-12  发布在  Java
关注(0)|答案(1)|浏览(291)

我已经启动了这个线程,在这个线程中我正在尝试连接到服务器,在收到响应之后,我必须用事件监听器更新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()概念,也尝试了join,但没有得到预期的帮助。谢谢你的帮助。

4nkexdtk

4nkexdtk1#

你可以使用倒计时锁

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();
            }
        }
    }

相关问题