BoBaH6eToH
BoBaH6eToH

Reputation: 58

The order of functions execution (multithreading)

I'm using Java.

I have a main function and function f(). Thread is created in f(), but it takes more time that other operations in f(). What is the true order of the сapital letters?

main() {
  operations A;
  f();
  operations B;
}

f() {
  C;
  final Thread thread = new Thread() {
        @Override
        public void run() {
          many operations, more than B+D;
          E;
        }
  };
  thread.start();
  D;
}

How would I make sure that order is A-C-D-B-E?

Upvotes: 0

Views: 54

Answers (1)

kennytm
kennytm

Reputation: 523344

You use a condition variable to ensure some code won't run before notified. Assuming the whole procedure is run only once,

volatile boolean canGoOn = false;
final Object condition = new Object();

// in main:
B;
synchronized (condition) {
    canGoOn = true;
    condition.notify();
}

// in thread:
synchronized (condition) {
    while (!canGoOn) {
        condition.wait();
    }
}
E;

(Not tested, you may need to catch some InterruptedException.)


BTW If you are using Android this whole idiom is packaged into the android.os.ConditionVariable class, which you just need to .open() it in main and .block() it in thread.

Upvotes: 1

Related Questions