java - Android Java Handler,线程同步块(synchronized block)(notifyall和Wait)

标签 java android handler wait

您好,这不是我的主要代码,但它足以显示我的问题。

我需要创建 UI 延迟(两次) - 一个接一个 我无法单独使用 handler.postDelay 来完成它。

所以我尝试用线程来制作它。

我想做的是让 t2 仅在 t1 结束后开始。

谁能帮帮我吗?

   final Handler handler1 = new Handler();
     final Handler handler2 = new Handler();


     synchronized(this)
     {


     Thread t1= new Thread(new Runnable() {

        public void run()
        {

            handler1.postDelayed(new Runnable() {
                @Override
                public void run() {
                    // Do something after 3s = 3000ms
                  imgB1.setBackgroundColor(Color.RED);
              notifyAll();
                }
            }, 3000);

        }
     });



     Thread t2= new Thread(new Runnable() {

        public void run()
        {

              handler2.postDelayed(new Runnable() {
                  @Override
                  public void run() {
                      // Do something after 3s = 3000ms
                      imgB1.setBackgroundColor(Color.YELLOW);
                      }
              }, 3000);

        }
       });



     t1.start();



     while (t1.isAlive()  )
     {
        try {
            wait();

        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
     }


     t2.start();

     }

最佳答案

保持简单:

  • 一个处理程序,无线程
  • 发布一个延迟的可运行程序,做两件事:
    1. 设置红色背景
    2. 发布另一个延迟的可运行文件(设置黄色背景)

final Handler handler1 = new Handler(Looper.getMainLooper());
handler1.postDelayed(new Runnable() {
            @Override
            public void run() {
                // Do something after 3s = 3000ms
              imgB1.setBackgroundColor(Color.RED);
              //post another action to be executed in 3 sec
              handler1.postDelayed(new Runnable() {
                  @Override
                  public void run() {
                      // Do something after 3s = 3000ms
                      imgB1.setBackgroundColor(Color.YELLOW);
                  }
              }, 3000);
            }
        }, 3000);

关于java - Android Java Handler,线程同步块(synchronized block)(notifyall和Wait),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26193079/

相关文章:

java - 即使有基本情况,我的代码也会导致 StackOverflowError

java - 在一份 testNG 报告中显示多个测试套件的所有失败测试

javascript - 使用 focusMode 约束获取所需的媒体设备

android - HTML5 应用的响应式网页设计高度单位

javascript - SharePoint 2013 View 中所有浏览器中的 .js MIME 类型错误

Java:允许在我的库存中进行放置操作?

android - 处理程序,我想定期运行

java - 使用 Guava 的 future 可迭代?

java - 无法应用 ContactEntry 中的 ContactEntry()

java - 按住按钮操作方法