01: /*
02: * @(#)Mutex.java 1.2 04/12/06
03: *
04: * Copyright (c) 1997-2004 Sun Microsystems, Inc. All Rights Reserved.
05: *
06: * See the file "LICENSE.txt" for information on usage and redistribution
07: * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
08: */
09: package pnuts.multithread;
10:
11: /**
12: * A simple mutex class
13: *
14: * @author Toyokazu Tomatsu
15: * @version 1.1
16: */
17: public class Mutex {
18: private boolean locked = false;
19: private boolean priv;
20: Thread owner;
21:
22: /**
23: * create mutex object
24: */
25: public Mutex() {
26: this (false);
27: }
28:
29: /**
30: * create mutex object
31: * @param priv If true a lock belongs to one owner otherwise not.
32: */
33: public Mutex(boolean priv) {
34: this .priv = priv;
35: }
36:
37: /**
38: * Lock it
39: * Be careful not to deadlock.
40: */
41: public synchronized void lock() throws InterruptedException {
42: while (locked) {
43: wait();
44: }
45: locked = true;
46: if (priv) {
47: owner = Thread.currentThread();
48: }
49: }
50:
51: /**
52: * Unlock it
53: */
54: public synchronized void unlock() {
55: if (!priv || Thread.currentThread() == owner) {
56: locked = false;
57: notifyAll();
58: }
59: }
60: }
|