我观察到以下情况:
synchronized
上问题是:是否可以进行“诚实”锁定,即按顺序授予锁定获取权?
测试代码:
public class HonestMutexTest {
private Object mSync = new Object();
private Object mSleep = new Object();
private void sleep(long millis) {
try {
Thread.sleep(millis);
}
catch (InterruptedException e) {
Assert.fail();
}
}
private void normalMutexesTestIteration() {
final StringBuilder states = new StringBuilder();
final Thread firstThread = new Thread(new Runnable() {
@Override
public void run() {
synchronized (mSync) { // 1
sleep(100);
states.append('1');
}
synchronized (mSync) {
states.append('2');
}
}
});
final Thread secondThread = new Thread(new Runnable() {
@Override
public void run() {
sleep(50);
synchronized (mSync) { // 2
states.append('3');
}
}
});
firstThread.start();
secondThread.start();
try {
firstThread.join(1000);
secondThread.join(1000);
}
catch (InterruptedException e) {
Assert.fail();
}
Assert.assertEquals(states.toString(), "123"); // what I expect here is "132"
}
@Test
public void testNormalMutexes() {
for (int i = 0; i < 10; ++i) {
normalMutexesTestIteration();
}
}
}