Let's say I've got this very simple code:
for(int i = 0; i < 10; i++) {
thread = new Thread(this);
thread.start();
}
However, in this code, the thread apparently starts 10 times at once and it doesn't wait before the previous one is finished. How do you check if the thread is finished before letting the thread start again?
The wait() Method Simply put, calling wait() forces the current thread to wait until some other thread invokes notify() or notifyAll() on the same object. For this, the current thread must own the object's monitor.
The wait() and join() methods are used to pause the current thread. The wait() is used in with notify() and notifyAll() methods, but join() is used in Java to wait until one thread finishes its execution.
Create an Object called lock . Then after runOnUiThread(myRunnable); , you can call lock. wait() .
wait() causes current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object. In other words, this method behaves exactly as if it simply performs the call wait(0). The current thread must own this object's monitor.
Before answering your question, I strongly encourage you to look into ExecutorServices
such as for instance the ThreadPoolExecutor
.
Now to answer your question:
If you want to wait for the previous thread to finish, before you start the next, you add thread.join()
in between:
for(int i = 0; i < 10; i++) {
thread = new Thread(this);
thread.start();
thread.join(); // Wait for it to finish.
}
If you want to kick off 10 threads, let them do their work, and then continue, you join
on them after the loop:
Thread[] threads = new Thread[10];
for(int i = 0; i < threads.length; i++) {
threads[i] = new Thread(this);
threads[i].start();
}
// Wait for all of the threads to finish.
for (Thread thread : threads)
thread.join();
If every thread must wait for the previous one to finish before starting, you'd better have one unique thread executing the original run method 10 times in sequence:
Runnable r = new Runnable() {
public void run() {
for (int i = 0; i < 10; i++) {
OuterClass.this.run();
}
}
}
new Thread(r).start();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With