【问题标题】:How to wait for a thread to start another one in Android?如何等待一个线程在Android中启动另一个线程?
【发布时间】:2015-01-26 17:26:08
【问题描述】:

每次单击按钮时都会调用此代码

   //Thread called when click a button
    Thread a = new Thread(new Runnable() {
        @Override
        public void run() {
            synchronized ((Object) contadordeMierda){
                Random rn = new Random();
                int n= rn.nextInt(10) + 1;
                contador++;

                try {
                    Thread.sleep(n*100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                System.out.println(contador);
            }
   }
    });

    a.start();

当我快速触摸它几次时,我得到了这个输出:

I/System.out﹕1

I/System.out﹕2

I/System.out﹕5

I/System.out﹕5

I/System.out﹕9

I/System.out﹕9

I/System.out﹕9

I/System.out﹕9

I/System.out﹕9

...

如何等待一个线程完成来启动另一个线程?所以打印出来 1 2 3 4 5 6 7 8 9 10 11 12...?

【问题讨论】:

  • 我不太确定 android,但我很难相信按钮点击是异步处理的,所以我怀疑线程没有以正确的顺序启动,但是相反,不能保证它们的执行顺序。使用带有单个支持线程或类似线程的 ExecutorService 可能会更好。 docs.oracle.com/javase/7/docs/api/java/util/concurrent/…
  • 你在哪里以及如何声明你的锁contadordeMierda
  • inside run(){ synchronized ((Object) contadordeMierda){...如果我不转换为 Object 它会显示错误
  • 您是否在按钮的 OnClickListerner 中声明了 contadordeMierda

标签: java android multithreading wait synchronize


【解决方案1】:

这正是join() function 的目的。多次提问:How to wait for a number of threads to complete?

【讨论】:

  • 我该如何使用它?以及如何保证 int 具有正确的值?
  • 在两个链接中都说明了如何使用它。如果您在线程内初始化int,则无法保证您的订单。将您的 int 放在线程范围之外或在开头将其传递给线程。
【解决方案2】:

为什么不这样做:只有在当前没有线程在运行时才让新线程启动:

private boolean isThreadRunning = false;//declare a boolean field to store thread status whether it's running or not
...

if(!isThreadRunning){
    Thread a = new Thread(new Runnable() {
        @Override
        public void run() {
            synchronized ((Object) contadordeMierda){
                Random rn = new Random();
                int n= rn.nextInt(10) + 1;
                contador++;

                try {
                    Thread.sleep(n*100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                System.out.println(contador);
                isThreadRunning = false;//Set the boolean variable to false because the thread has completed it's operations.
            }
   }
    });

    a.start();
    isThreadRunning = true;// Set the boolean to true because thread.start has been called.

}

【讨论】:

  • 我不能这样做,因为我希望线程按顺序在第一个线程之后开始
猜你喜欢
  • 2012-01-07
  • 1970-01-01
  • 2017-09-28
  • 1970-01-01
  • 1970-01-01
  • 2011-09-03
  • 2011-07-10
  • 1970-01-01
  • 2019-01-03
相关资源
最近更新 更多