简体   繁体   English

等到所有线程都在等待之前,先通知

[英]Wait until all threads are waiting before first notify

In MyClass I create several threads in a loop like so: MyClass我像这样在循环中创建多个线程:

for(int i = 0; i < 4; i++)
{
    threads[i] = new Thread(new MyRunnable(lock));
    threads[i].start();
}

where lock is a property of MyClass , and each of these threads, in their run method, calls lock.wait() . 其中lockMyClass的属性,并且每个线程在其run方法中都调用lock.wait()

After I've created these threads I want to assign one of them control of the lock. 创建完这些线程后,我想分配其中一个锁控制权。 I tried simply putting lock.notify() after the loop, but this runs too soon - although it's after the loop, none of the threads have yet executed lock.wait() , so they all miss the lock.notify() , and then wait indefinitely for another one that never comes. 我试着简单地将lock.notify()放在循环之后,但这运行得太早了-尽管它在循环之后,但没有一个线程执行过lock.wait() ,所以它们都错过了lock.notify()和然后无限期地等待另一个永远不会到来的。

I can halt execution of the main thread for a bit, eg execute Thread.sleep(1000) before I call lock.notify() . 我可以暂停主线程的执行,例如在调用lock.notify()之前执行Thread.sleep(1000) lock.notify() This works as it gives the threads a chance to get to the wait ing stage before notify ing them. 之所以起作用,是因为它使线程有机会在notify它们之前进入wait阶段。 But this doesn't seem very elegant, and obviously I'd rather not halt the main execution of my program like this. 但这似乎不太优雅,显然我不希望这样停止程序的主要执行。

How should I achieve this? 我应该如何实现呢?

You could use some more high-level constructs from the concurrency package, such as a Semaphore . 您可以使用并发包中的一些更高级的构造,例如Semaphore

So you'd set up the Semaphore with a single "permit" before your loop, pass it to your threads, and then all of them would try to "acquire" that permit (which only one of them can do, the others will fail at that). 因此,您需要在循环之前使用一个“许可”来设置信号量,然后将其传递给线程,然后所有这些人都将尝试“获取”该许可(其中只有一个可以执行,其他会失败)在那个)。

Even Semaphore is kind of low-level, usually you can find something even more tailored to your actual application, such as blocking queues or concurrent collections. 甚至Semaphore都是低级的,通常您可以找到更适合您的实际应用程序的内容,例如阻塞队列或并发集合。

Have a look at Thread.join() method which can help you to make wait current thread, until thread which invoked this method is not completed. 看一下Thread.join()方法,该方法可以帮助您等待当前线程,直到调用此方法的线程未完成为止。

Example: 例:

Thread t1 = new Thread();
Thread t2 = new Thread();
t1.start();
t1.join();
t2.start();

Here t2 will wait for the completion of t1 . 这里t2将等待t1完成。 More about it, you can read here . 有关它的更多信息,您可以在这里阅读。

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

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