import java.io.*;
public class Mutex {
Thread owner = null;
public String toString() {
String name;
if (owner == null)
name = "null";
else
name = owner.getName();
return "<" + super.toString() + "owner:" + name +">";
}
// Note that if we are interrupted, we will simply resend that
// interrupt to ourselves AFTER we've locked the mutex.  The
caller
// code will have to deal with the interrupt.
public synchronized void lock() {
boolean interrupted = false;
while (owner != null) {
try {
wait();
} catch (InterruptedException ie) {
interrupted = true;
}
}
owner = Thread.currentThread();
if (interrupted)
Thread.currentThread().interrupt();
}
public synchronized void unlock() {
if (!owner.equals(Thread.currentThread()))
throw new IllegalMonitorStateException("Not owner");
owner = null;
notify();
}
}
//
Extensions/ConditionVar.java
/*
A Pthreads style condition variable.
Note that if you use these, you must handle InterruptedException
carefully. condWait() will return as if from a spurious wakeup
if interrupted. If your code allows interrupts to be sent, you
MUST look at InterruptedException inside the while() loop:
while (!condition) {
condWait(m);
Search WWH :
Custom Search
Previous Page
Multithreaded Programming with JAVA - Topic Index
Next Page
Multithreaded Programming with JAVA - Bookmarks
Home