ITeye博客

一个java 线程互斥体

absolute · 2007-11-22 10:56 · Java记事本 · Markdown

java 代码

  1. package test;
  2. public final class Mutex {
  3. private long locks;
  4. private Thread owner;
  5. public synchronized void lock() {
  6. Thread currentThread = Thread.currentThread();
  7. while (locks > 0 && currentThread != owner) {
  8. try {
  9. 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. }

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。