龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > 软件开发 > JAVA开发 >

Java多线程同步-BusyFlag或Lock

时间:2009-12-23 15:42来源:未知 作者:admin 点击:
分享到:
我们首先开发一个BusyFlag的类,类似于C++中的Simaphore。 public class BusyFlag{ protected Thread busyflag= null ; protected int busycount=0; public synchronized void getBusyFlag(){ while (tryGetBusyFlag()== false ){ try { wai

  我们首先开发一个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. }

  
  

精彩图集

赞助商链接