Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我有一个启动线程的方法,并且我希望该方法阻塞,直到线程完成其设置阶段,否则将面临竞争条件。
我知道我想使用等待通知,但我不知道如何拥有监视器等等。
如果只有启动线程需要等待,我通常使用倒计时锁存器。
那里有示例,但如果您需要,我可以快速举出一个示例。
或者,如果多个线程可能使用线程并且需要知道它何时初始化,则可以使用屏障。
将您的“设置阶段”移出run()和移入init()方法。
run()
init()
MyRunnableClass mrc = new MyRunnableClass(); mrc.init(); Thread t = new Thread(mrc); t.start();
编辑:或者正如@Buhb 在下面的评论中指出的那样,只需将它放在构造函数中。多年的 C++ 让旧习惯很难改掉。