Java Thread:(2) wait() and notif

2021-04-29  本文已影响0人  戈壁堂

Java Thread:(1) synchronization

中的实现版本使用sleep方法进行等待,造成了CPU的浪费。使用wait()notify()机制优化如下——

public class BusyFlag {

    protected Thread busyflag = null;
    protected int busycount = 0;


    public synchronized void  getBusyFlag() {
        while (!tryGetBusyFlag()) {
            try {
                wait();
            } catch (Exception e) {}
        }
    }

    public 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 (getBusyFlagOwner() == Thread.currentThread()) {
            busycount--;
            if (busycount == 0) {
                busyflag = null;
                notify();
            }
        }
    }
    public synchronized Thread getBusyFlagOwner() {
        return busyflag;
    }
}

在内部实现上,wait()notify()通常都是通过控制变量来实现的。所以这要求对这两个方法的调用需要加锁,确保内部对变量的操作是原子的。

上一篇下一篇

猜你喜欢

热点阅读