Java Reference
In-Depth Information
package com.oozinoz.applications;
import java.util.*;
public class ShowConcurrentMutex implements Runnable
{
private List list;
private Object mutex = new Object();
protected static List upMachineNames()
{
//... as before
}
protected void go()
{
list = upMachineNames();
synchronized (mutex) {
Iterator i = list.iterator();
int j = 0;
while (i.hasNext())
{
j++;
if (j == 1)
{
new Thread(this).start();
}
System.out.println(i.next());
}
}
}
public void run()
{
synchronized (mutex)
{
list.add(0, "Fuser1101");
}
}
public static void main(String[] args)
{
new ShowConcurrentMutex().go();
}
}
This program will print the original list, because the run() logic must wait for the mutex
monitor:
Mixer1201
ShellAssembler1301
StarPress1401
UnloadBuffer1501
This output is correct, but you will usually not want other threads to block while one thread
iterates over a collection. It may be more effective to clone the collection in a synchronized
operation and then work on the clone. The interfaces List and Set are not cloneable, but the
implementing classes ArrayList and HashSet are.
Search WWH ::




Custom Search