Java多线程同步-BusyFlag或Lock
2008-01-05 19:23:07 来源:WEB开发网核心提示:我们首先开发一个BusyFlag的类,类似于C++中的Simaphore,Java多线程同步-BusyFlag或Lock,public class BusyFlag { PRotected Thread busyflag = null; protected int busycount = 0; public sync
我们首先开发一个BusyFlag的类,类似于C++中的Simaphore。
- public class BusyFlag {
- PRotected Thread busyflag = null;
- protected int busycount = 0;
- public synchronized void getBusyFlag() {
- while (tryGetBusyFlag() == false) {
- try {
- wait();
- } catch (Exception e) {}
- }
- }
- private synchronized boolean tryGetBusyFlag() {
- if (busyflag == null) {
- busyflag = Thread.currentThread();
- busycount = 1;
- return true;
- }
- if (busyflag == Thread.currentThread()) {
- busycount++;
- return true;
- }
- return false;
- }
- public synchronized void freeBusyFlag() {
- if(getOwner()== Thread.currentThread()) {
- busycount--;
- if(busycount==0) {
- busyflag = null;
- notify();
- }
- }
- }
- public synchronized Thread getOwner() {
- return busyflag;
- }
- }
更多精彩
赞助商链接