2

I have this code below, that evaluates if three threads are done, and if yes, it continues with the code. The problem is that when I include some sort of print statement before the if statement, it works as usual. However, when I don't include the print, it continues forever. Here it is:

while (!are_we_done) {
    System.out.println(are_we_done);
    if (thread_arr[0].are_we_done==true && thread_arr[1].are_we_done==true && thread_arr[2].are_we_done==true) {
        are_we_done=true;
    }
}

Any clue as to what's going on? Thanks in advance for any help/advice.

1

2 Answers 2

3

The problem was that I had to specify the are_we_done variable in the thread class as volatile.

Sign up to request clarification or add additional context in comments.

Comments

0

Your work with threads is awesome - google for 'busy waiting'.

  • in main thread introduce 'latch = new CountDownLatch(<number of threads>)' variable
  • pass it into all your threads
  • on finish of the thread call 'latch.countDown()'
  • in main thread wait for all spawned threads complete with 'latch.await(...)'

Example:

public static void main(String... args) throws Exception {
    Thread[] threads = new Thread[3];
    CountDownLatch latch = new CountDownLatch(threads.length);

    for (int i = 0; i < threads.length; i++) {
        threads[i] = new Thread(new YourRunnable(latch));
        threads[i].start();
    }

    while (!latch.await(1000)) {
        System.out.println("Not complete yet");
    }

    System.out.println("Complete!");
}

public class YourRunndable implements Runnable {
    ... // fields + constructor

    public void run() {
        try {
            ... // do your staff
        } finally {
            latch.countDown();
        }
    }
}

2 Comments

In that case, how do I transfer information from the threads in the array to the main thread?
in short - use shared data structures (e.g. collections, queues, fields). read this tutorial - it is the best guide for multi-threading. an hour of reading and testing, but much simpler to live further.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.