- 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();
- }
- }
- }
一個java 線程互斥體
java 代碼
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.