---
title: "一个java 线程互斥体"
author: "absolute"
date: "2007-11-22T10:56:17Z"
tags: []
slug: "java"
draft: false
lastmod: "2007-11-22T10:56:17Z"
id: 142508
url: "https://absolute.iteye.com/blog/142508"
---

java 代码

01. package test;
02. public final class Mutex {
03. private long locks;
04. private Thread owner;
05. public synchronized void lock() {
06. Thread currentThread = Thread.currentThread();
07. while (locks &gt; 0 && currentThread != owner) {
08. try {
09. wait();
10. } catch (InterruptedException e) {
11. }
12. }
13. owner = currentThread;
14. locks++;
15. }
16. public synchronized void unlock() {
17. Thread currentThread = Thread.currentThread();
18. if (locks == 0 && owner != currentThread) {
19. return;
20. }
21. locks--;
22. if (locks == 0) {
23. owner = null;
24. notifyAll();
25. }
26. }
27. }