一個java 線程互斥體

java 代碼
  1. package test;   
  2.   
  3. public final class Mutex {   
  4.     private long locks;   
  5.     private Thread owner;   
  6.   
  7.     public synchronized void lock() {   
  8.         Thread currentThread = Thread.currentThread();   
  9.         while (locks > 0 && currentThread != owner) {   
  10.             try {   
  11.                 wait();   
  12.             } catch (InterruptedException e) {   
  13.   
  14.             }   
  15.         }   
  16.         owner = currentThread;   
  17.         locks++;   
  18.     }   
  19.   
  20.     public synchronized void unlock() {   
  21.         Thread currentThread = Thread.currentThread();   
  22.         if (locks == 0 && owner != currentThread) {   
  23.             return;   
  24.         }   
  25.         locks--;   
  26.         if (locks == 0) {   
  27.             owner = null;   
  28.             notifyAll();   
  29.         }   
  30.     }   
  31. }   
發佈了19 篇原創文章 · 獲贊 0 · 訪問量 3099
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章