如何使Java线程获得锁定以便他们尝试获取它?

时间:2016-01-06 16:41:50

标签: java multithreading

我观察到以下情况:

  • Thread_1获取锁定同步对象,做一些工作
  • 当Thread_1占用锁定时,Thread_2尝试获取相同的锁定,卡在synchronized
  • Thread_1释放锁定,相对较快地做某事(没有屈服或睡觉),然后再次获得相同的锁定
  • Thread_2保持等待状态(原因是如果调度程序在同步对象可以自由处理的这么短的时间内没有切换到Thread_2)

问题是:是否可以进行“诚实”锁定,即按顺序授予锁定获取权?

测试代码:

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();
    }
  }
}

0 个答案:

没有答案