// This example is from the book _Java Threads_ by Scott Oaks and Henry Wong.
// Written by Scott Oaks and Henry Wong.
// Copyright (c) 1997 O'Reilly & Associates.
// You may study, use, modify, and distribute this example for any purpose.
// This example is provided WITHOUT WARRANTY either expressed or implied.
// Sample BusyFlag -- Chapter 3, p. 60. This is the final BusyFlag example
// for this chapter, but it still contains a bug (see the BusyFlag for
// chapter 4).
public class BusyFlag {
private Thread busyflag = null;
private int busycount = 0;
public void getBusyFlag() {
while (tryGetBusyFlag() == false) {
try {
Thread.sleep(100);
} catch (Exception e) {}
}
}
public synchronized boolean tryGetBusyFlag() {
if (busyflag == null) {
busyflag = Thread.currentThread();
busycount = 1;
return true;
}
if (busyflag == Thread.currentThread()) {
busycount++;
return true;
}
return false;
}
public synchronized void freeBusyFlag () {
if (getBusyFlagOwner() == Thread.currentThread()) {
busycount--;
if (busycount == 0) busyflag = null;
}
}
public synchronized Thread getBusyFlagOwner() {
return busyflag;
}
}
|