首页 > 学院 > 开发设计 > 正文

Java多线程同步-BusyFlag或Lock

2019-11-18 10:46:50
字体:
来源:转载
供稿:网友

我们首先开发一个BusyFlag的类,类似于C++中的Simaphore。

  1. public class BusyFlag {
  2.     PRotected Thread busyflag = null;
  3.     protected int busycount = 0;
  4.     
  5.     public synchronized void getBusyFlag() {
  6.         while (tryGetBusyFlag() == false) {
  7.             try {
  8.                 wait();
  9.             } catch (Exception e) {}            
  10.         }
  11.     }
  12.     
  13.     private synchronized boolean tryGetBusyFlag() {
  14.         if (busyflag == null) {
  15.             busyflag = Thread.currentThread();
  16.             busycount = 1;
  17.             return true;
  18.         }
  19.         
  20.         if (busyflag == Thread.currentThread()) {
  21.             busycount++;
  22.             return true;
  23.         }
  24.         return false;        
  25.     }
  26.     
  27.     public synchronized void freeBusyFlag() {
  28.         if(getOwner()== Thread.currentThread()) {
  29.             busycount--;
  30.             if(busycount==0) {
  31.                 busyflag = null;
  32.                                      notify();
  33.                             }
  34.         }
  35.     }
  36.     
  37.     public synchronized Thread getOwner() {
  38.         return busyflag;
  39.     }
  40. }



发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表