简体   繁体   中英

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 ACDBE?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM