`
absolute
  • 浏览: 188243 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

一个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. }   
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics