我没有看到您的代码,但如果我理解正确,您可以在这种情况下使用静态锁。下面的代码适用于单个仪表母级。此代码使同一时间只有一个乐器父乐器在演奏,一个乐器演奏完后,等待的乐器将逐一演奏。
private static boolean canPlay = true;
private static Object playLock = new Object();
@Override
public void run() {
checkPlayable();
try {
// your code
}
finally { // If a exception happens(or not) during the execution of the code block above, lock must be released.
synchronized (playLock) {
canPlay = true; // enable playing for others
playLock.notifyAll(); // wake up others
}
}
}
/*
* This is used to get the lock for the first one to come. Makes other ones wait.
*/
private static void checkPlayable() {
synchronized (playLock) {
while(!canPlay) {
try {
playLock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
canPlay = false;
}
}