简体   繁体   中英

Wait until all threads are waiting before first notify

In MyClass I create several threads in a loop like so:

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() .

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.

I can halt execution of the main thread for a bit, eg execute Thread.sleep(1000) before I call lock.notify() . This works as it gives the threads a chance to get to the wait ing stage before notify ing them. 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 .

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.

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.

Example:

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

Here t2 will wait for the completion of t1 . More about it, you can read here .

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