簡體   English   中英

如何等待線程在Android中啟動另一個線程?

[英]How to wait for a thread to start another one in Android?

每次單擊按鈕時都會調用此代碼

   //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 ...?

這是join()函數的確切目的。 多次問到問題: 如何等待多個線程完成?

為什么不這樣做:您僅在當前沒有線程在運行時才啟動新線程:

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.

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM