简体   繁体   English

函数执行的顺序(多线程)

[英]The order of functions execution (multithreading)

I'm using Java. 我正在使用Java。

I have a main function and function f(). 我有一个主要功能和功能f()。 Thread is created in f(), but it takes more time that other operations in f(). 线程是在f()中创建的,但是它比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? 我如何确定该订单为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.) (未经测试,您可能需要捕获一些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. 顺便说一句,如果您使用的是Android,则整个成语都打包在android.os.ConditionVariable类中,您只需要在main .open()和在线程中将.block()打包即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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