java 代码
- package test;
- public final class Mutex {
- private long locks;
- private Thread owner;
- public synchronized void lock() {
- Thread currentThread = Thread.currentThread();
- while (locks > 0 && currentThread != owner) {
- try {
- wait();
- } catch (InterruptedException e) {
- }
- }
- owner = currentThread;
- locks++;
- }
- public synchronized void unlock() {
- Thread currentThread = Thread.currentThread();
- if (locks == 0 && owner != currentThread) {
- return;
- }
- locks--;
- if (locks == 0) {
- owner = null;
- notifyAll();
- }
- }
- }