我需要優先構建我所謂的「不公平信號」。 例如:當一個線程與priority = 1
想要獲得信號量,它只需要等到具有相同優先級的其他線程完成,那麼它可以acquire()
。但是當priority = 2
的線程想要獲取信號量時,它必須等待所有使用priority = 1
的線程在使用信號量之前完成,然後嘗試acquire()
。 我總共有4個不同的優先級。 這是我試過的,但沒有奏效。互斥優先於JAVA
有人有任何解決方案嗎?
public class UnfairSemaphore
{
private Semaphore mPrior1;
private Semaphore mPrior2;
private Semaphore mPrior3;
private Semaphore mPrior4;
public UnfairSemaphore()
{
mPrior1 = new Semaphore(1);
mPrior2 = new Semaphore(1);
mPrior3 = new Semaphore(1);
mPrior4 = new Semaphore(1);
}
public void acquire(int priority) throws InterruptedException
{
if(priority == 1)
{
mPrior1.acquire();
}
else if(priority == 2)
{
while(mPrior1.hasQueuedThreads() && mPrior1.availablePermits() <=0)
{
//wait();
}
mPrior2.acquire();
mPrior1.acquire();
}
else if(priority == 3)
{
while(mPrior1.hasQueuedThreads() && mPrior1.availablePermits() <=0 && mPrior2.hasQueuedThreads() && mPrior2.availablePermits() <=0)
{
//wait();
}
mPrior3.acquire();
mPrior2.acquire();
mPrior1.acquire();
}
else
{
while(mPrior1.hasQueuedThreads() && mPrior1.availablePermits() <=0 && mPrior2.hasQueuedThreads() && mPrior2.availablePermits() <=0 && mPrior3.hasQueuedThreads() && mPrior3.availablePermits() <=0)
{
//wait();
}
mPrior4.acquire();
mPrior3.acquire();
mPrior2.acquire();
mPrior1.acquire();
}
}
public void release(int priority)
{
if(priority == 1)
{
mPrior1.release();
}
else if(priority == 2)
{
mPrior1.release();
mPrior2.release();
}
else if(priority == 3)
{
mPrior1.release();
mPrior2.release();
mPrior3.release();
}
else
{
mPrior1.release();
mPrior2.release();
mPrior3.release();
mPrior4.release();
}
//notifyAll();
}
}
「但它沒有奏效」它做了什麼呢? –