After seaching a lot and not finding a concrete answer
If I have two threads started:
Thread t1 = new Thread();
Thread t2 = new Thread();
t1.start();
t2.start();
After starting the threads I need the main thread to wait for these two thread to finish before printing the final result
How can I make the main thread wait for both t1 and t2?
A plain wait() would be enough?
Add
t1.join();
t2.join();
in your thread which should wait till t1 and t2 will finish their tasks (in your case call it from your main thread).
The answer depends...
You could
Use a CountDownLatch which is probably the simplest solution.
This way you would simply wait on the latch until it has been signaled the prescribed number of times (by each Thread terminating). This scales quite nicely as you increase the number of threads...
You could
Use join, but it would become tedious as you add more threads
You could
Add each Thread to a List, loop through the list, removing those threads that are no longer alive and keep looping until the List is empty, but that's a rather heavy handed approach.
You could
Combine the above solution with some kind of monitor lock which the loop would wait on and each Thread would notify when they complete, but it's not much cleaner and you could still end up waiting for non-existent threads...
You could
Use an ExecutorService and either use it's invokeAll and/or shutdown methods. See Executors for more details. This also scales quite nicely and even has the added benefit of allowing you to use a Thread pool to better manage the system resourcs
Check out the Thread#join method.
Also, you might find using an ExecutorService (and friends) helpful. Its essentially thread pool/management and provides a lot of conveniences and IMO a cleaner API than threads. Barrier to entry is low...
You want Thread#join(). wait() is for signalling, join() is to wait for the thread to finish.
Related
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, e.g. execute Thread.sleep(1000) before I call lock.notify(). This works as it gives the threads a chance to get to the waiting stage before notifying 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.
So I'm still a bit new to multithreading and came across these two classes. What I understood is that an ExecutorService can be a thread pool and via the awaitTermination method the thread in which it is called comes to a halt until the threads in the thread pool have finished running.
Then there is the CountDownLatch you can give to your Runnables. These can then in turn call the countDown() method. If you then use the await() method in your main thread, this thread will come to a halt until the countdown has reached zero.
I don't seem to spot the difference in result between the two ways? Why would I ever use a CountdownLatch?
There are lots of different things where you might want to wait for lots of things to be processed that don't involve shutting down your thread pool.
For example you might have 5 servers that you are monitoring, with a thread to monitor each one. A Countdown Latch is used to fire off another thread once all the first 5 have connected.
It can also be used in many other situations, for example if you have some initialization to happen then all the threads may wait on the countdown latch until all the initialization has finished and the latch is counted down to zero.
My problem is, I have two threads t1 and t2. Both of them make some calculations, and according to my program, I want to use a concurrency technique that blocks till t1 and t2 both finish their tasks and then continue.
I tried countdownLatch, and I read about ExecutorService and made a small example. Concerning the ExecutorService I did something like the following:
executor.execute(new RunnableClass(bgr,3))
executor.execute(new RunnableClass(bgr,7))
executor.shutdown();
if (executor.isTerminated()) {
print("terminated")
}
and the word "terminated" was never printed, which means executorService object does not block.
please let meknow whih concurrency technique i should use to suit my situation
Reading the documentation is always going to clarify things before you start coding..
But just wanted to share a few points :
1.) CountDownLatch can be a solution for your problem. Read this link before you code..
http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/CountDownLatch.html
Basically the concept is that you have latch your program in a fixed state and stop it from proceeding until the latch is released.
So you have 2 threads...set a countdownlatch value of 2. Make both the threads decrement the value after they are done. Till the latch value is decremented to 0 the main thread will be waiting for this to take place.
executor.shutdown....refer documentation...it says that it waits for all submitted tasks to complete before it shutsdown.
When waiting for other threads to finish, we can use either join or CountdownLatch. What are the pros and cons of using either of those two mechanisms?
You can only use Thread.join if you're handling the threads yourself. Most people choose not to deal with the minutia of thread handling directly, and instead use an ExecutorService to handle it for them. ExecutorServices do not directly reveal how they are executing tasks, so you would have to use a CountDownLatch: (Assuming you don't want to just shutdown the whole service, that is.)
ExecutorService service = Executors.newFixedThreadPool(5);
final CountDownLatch latch = new CountDownLatch(5);
for(int x = 0; x < 5; x++) {
service.submit(new Runnable() {
public void run() {
// do something
latch.countDown();
}
});
}
latch.await();
Another difference is after join(), thread can be unblocked only when joined thread has finished its execution while in CountDownLatch a thread can decrease the count anytime either on completion of thread or in between based on any condition.
This way we can get better control over unblocking of the thread instead of solely depending on the completion of joined thread.
join() is waiting for another thread to finish while CountDownLatch is designed for another purpose. If using CountDownLatch, You don't have to have reference of threads for which you are waiting as we have to do using join(). Let's assume you want to start a game when at least 2 players should be available. You can use countdownlatch in this case. But you can't achieve this using join easily because you don't have another thread(player in this case) on which you can write join().
A CountdownLatch is task-oriented - it's thread-agnostic. A whole pile of unrelated sets of tasks can be submitted to a threadPool and a CountdownLatch will ensure that each set notifies the originator of completion. Join() is an annoying abberation that links tasks to threads and, simply put, should never have entered the language in the first place. Sadly, a large, steaming pile of thread-tutorials mention Join() on the first page, thereby introducing threads to newbies as a deadlock-generator and generating thread-funk :(
CountdownLatchallows you to change the implementation of Item to maybe submit to an Executor service instead of using Threads directly.
The CountDownLatch class allows us to coordinate the starting and stopping of threads. Typical uses are as follows:
We can make several threads start at the same time;
We can wait for
several threads to finish (whereas, for example, the Thread.join()
method only lets you wait for a single thread).
You can have a look at this -> http://javahowto.blogspot.com/2011/08/when-to-join-threads-with.html
And this ->
A CountDownLatch's latch.await() method vs Thread.join()
I have some developpements to do and I try to see if there is a desing pattern to use.
The problem is simple:
I have a main thread that launches many treads. The main thread must wait for each thread to finish and then doing something else.
The existing code it's a bit ugly. I have a while loop that check a thread group to see if is something running:
//launch threads
.....
//wait for threads to finish
while (ThreadRepository.getInstance().isActiveThreadGroup(myGroupId)) {
Thread.sleep(5000);
}
//doing something else
So, as you see, the while loop keeps running until no threads running.
I was thinking at the pattern producer-consumer and I would like to do something like that:
Using some BlockingQueue for instance, and each thread put (or take) something in it.
Instead of having the while and sleep I would like to have something like
myQueue.take() but something to wait for the queue to be empty.
When empty, it means no threads running.
I try to search on the Internet but I did not found something that matches my problem.
Does anyone know the most efficient to solve my problem ?
There are two easy ways to have one thread wait for N threads to finish:
Make the main thread call join() on all the other threads. join() returns when a thread finishes, or has already finished
Create a CountDownLatch initialized to N, pass this latch to all the threads, make each thread call countDown() on the latch when it has finished, and make the main thread call await() on the latch. This second technique is a bit harder than the first one, but is also more flexible and reusable, and allows being awaken after some delay, even if the N threads have not finished yet.
You can use BlockingQueue as follows:
each child thread puts a message in the queue when finished
the main thread takes messages from the queue and counts them. When the number of messages equals the number of threads, all threads has finished.