How to synchronize 4 threads.

J

jseidelREMOVECAPS

I need to synchronize 4 different threads. I dont think wait() and
notifyall() will work.

Could someone explain how to do this?

Jerry
 
E

Eric Sosman

I need to synchronize 4 different threads. I dont think wait() and
notifyall() will work.

Could someone explain how to do this?

If by "synchronize" you mean you want each thread to
run until it reaches a certain point in its execution and
then pause there until the other three have reached their
corresponding points, try something like this:

public class Barrier {
private int count;

public Barrier(int count) {
if (count <= 0)
throw new IllegalArgumentException();
this.count = count;
}

synchronized
public void stall() {
if (count <= 0)
throw new IllegalStateException();
--count;
while (count > 0) {
try {
wait();
}
catch (InterruptedException ex) {
// who cares?
}
}
notifyAll();
}
}

If you mean something else, you'll need to explain it.
 
J

jseidelREMOVECAPS

I am running 4 and sometimes more threads. Each thread needs to
iterate through a Hashmap. And 3 threads add and remove from the
hashmap. I want to prevent a thread from iterating during an add or
remove operation. Do I need to run them one at a time? and if so,
how. Im fairly new to threads.

Thank you

Jerry
 
K

Kevin McMurtrie

I am running 4 and sometimes more threads. Each thread needs to
iterate through a Hashmap. And 3 threads add and remove from the
hashmap. I want to prevent a thread from iterating during an add or
remove operation. Do I need to run them one at a time? and if so,
how. Im fairly new to threads.

Thank you

Jerry

They should all synchronize on a common object, like the Hashmap itself,
during their operations on it. Only one thread will be able to enter
the synchronized block at a time.

If the computations are very long, like database lookups, synchronize on
the Hashmap while transferring batches of work data to/from it. You can
then perform lengthy processing on the local batch copy without holding
a lock on the shared Hashmap. You can also swap the Hashmap references
during a synchronization lock but you'll need to use some other object
for synchronization.

Also check out wait() and notify() while you're learning about threads.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,680
Members
48,796
Latest member
Greg L.

Latest Threads

Top