2017-06-24 12 views
0

メソッドがtrueを返すまでforループを待ちたいです。 EG-メソッドがtrueを返すまでforループを待ちます。

for(int i = 0; i < 100; i++) 
    { 
     // for loop should get executed once 

      my_method(i); //this method is called 

     // now for loop should wait till the above method returns true 

     // once the method returns true the for loop should continue if the condition is true 

    } 

    public boolean my_method(int number) 
    { 
     // my code 
     return true; 
    } 

については

私がtrueを返すために取る)(my_methodますどのくらいかわかりません。

上記のコードはすべてAsyncTask内にあります。

私はAndroid開発の初心者です。本当にありがとうございました。要求されたとして

+0

ではなく、メインスレッドAsyncTaskで行きます。 –

+1

'AsyncTask'を使用している場合は、非同期に行われる操作に頼らなければなりません。あなたが求めたのは、同期操作のためのものです。 'for-loop'の前に' my_method() 'を呼び出すことができ、' true'を返すとループを開始します。あなたの現在のコードはこのメソッドを100回呼びます。これはあなたが望むものではないと思います。 – Merka

+0

ロックを使用してロックを待ちます。 – mikep

答えて

0

private final ReentrantLock lock = new ReentrantLock(); 
private final Condition done = lock.newCondition(); 
for(int i=0;i<100;i++) 
{ 
    // for loop should get executed once 
lock.lock(); 
    try { 
     my_method(i, lock); //this method is called 
    done.await(); 
    } finally { 
      lock.unlock(); 
     } 

    // now for loop should wait till the above method returns true 

    // once the method returns true the for loop should continue if the condition is true 

} 

public boolean my_method(int number, ReentrantLock lock) 
{ 
    lock.lock(); 
    try { 
    // my code 
     done.signal(); 
    } finally { 
     lock.unlock(); 
    } 
return true; 
} 
+0

あなたはおそらく、非同期の結果を待つためにスレッドを遅らせることは、Androidでのやり方ではなく、99%のケースであると言及するべきです。 – Henry

+0

ありがとうございます。ロックとアンロックを何度も使用すると、このコードは機能しますか? – Rahulrr2602

+0

@mikepあなたの答えを試しましたが、my_method()は一度だけ実行されます。 – Rahulrr2602

関連する問題