• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

186
Views
Custom Way to Wait for all thread to complete in Java?

After Starting the thread object

thread1.start();
thread2.start(); 

i need to wait for the finalization of both threads using the join() method(the most common way).

Like this.

try {
      thread1.join();
      thread2.join();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }

All the tutorial i see uses some inbuilt method for finalization of threads.

Is there a way to wait for thread finalization without using any inbuilt method like join or executor ?

about 3 years ago · Santiago Trujillo
1 answers
Answer question

0

Every Thread has a state. NEW , RUNNABLE , BLOCKED , WAITING , TIMED_WAITING , or TERMINATED

TERMINATED is a state that you can look for every thread with thread.getState() method, which is the state of thread once it finish execution

// 2 Thread Object 
            Thread threads[] = new Thread[2];
            // store Thread Statuses
            Thread.State status[] = new Thread.State[2];

Since All Thread have state. Before starting thread store their state

for (int i = 0; i < 2; i++) {
        status[i] = threads[i].getState();
                }

Once you start the thread The finished Thread has a state of Terminated, you can use it to and write your own check for finalization

    // custom way for finalization of the threads
     boolean finish = false; // initially all non finised 
     while(!finish) {
            for (int i = 0; i < 2; i++) {
                if (threads[i].getState() != status[i]) {
                    status[i] = threads[i].getState();
                    }
                }
            finish = true;
            for (int i = 0; i < 2; i++) {
            finish = finish && (threads[i].getState() ==
                                State.TERMINATED);
                }
 }
about 3 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error