1

I create 4 threads to do 4 operations. When all threads complete execution,I want to notify main thread. How to know if all thread complete?

Here is my code:

public class TestActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);

        /*
        * create 4 threads to do 4 operations
        * */
        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {} // do operation 1
        });
        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {} // do operation 2
        });
        Thread thread3 = new Thread(new Runnable() {
            @Override
            public void run() {} // do operation 3
        });
        Thread thread4 = new Thread(new Runnable() {
            @Override
            public void run() {} // do operation 4
        });

        thread1.start();
        thread2.start();
        thread3.start();
        thread4.start();

    }
}
Aswin P Ashok
  • 702
  • 8
  • 27
Chan Myae Aung
  • 547
  • 3
  • 15
  • Its simple I guess. Thread destroy itself when it reaches its last line of execution. – mudit_sen Sep 16 '17 at 06:58
  • create another "master" thread that calls `thread1.join()`, `thread2.join()` etc, after joining 4 of them you know that they finished – pskink Sep 16 '17 at 07:00
  • may this link will help [check for your answer](https://stackoverflow.com/questions/26578368/how-does-a-thread-notify-the-main-thread-while-the-main-thread-is-still-running#answer-26578424) – Arpit Prajapati Sep 16 '17 at 07:01
  • What about a listener? Add one to every Thread... See this: https://stackoverflow.com/questions/702415/how-to-know-if-other-threads-have-finished – deHaar Sep 16 '17 at 07:04
  • Use invokeAll() of ExecutorService API. Refer to this post : https://stackoverflow.com/questions/18202388/how-to-use-invokeall-to-let-all-thread-pool-do-their-task/39547616#39547616 – Ravindra babu Sep 17 '17 at 21:22

1 Answers1

2

Try using join method of Thread. Here is an example,

thread1.start();
thread2.start();
thread3.start();
thread4.start();

while (true) {
    try {
        thread1.join();
        thread2.join();
        thread3.join();
        thread4.join();
        break;
    } catch (InterruptedException e) {
        e.printStackTrace();
}
Indra Basak
  • 7,124
  • 1
  • 26
  • 45