正在阅读:攻克学习多线程时碰到的难题攻克学习多线程时碰到的难题

2004-03-26 10:05 出处:PConline 作者:qlampskyface 责任编辑:linjixiong

  class FineGrainLock {

   MyMemberClass x, y;
   Object xlock = new Object(), ylock = new Object();

   public void foo() {
      synchronized(xlock) {
         //access x here
      }

      //do something here - but don't use shared resources

      synchronized(ylock) {
         //access y here
      }
   }

   public void bar() {
      synchronized(this) {
         //access both x and y here
      }
      //do something here - but don't use shared resources
   }
  }

    4.synchronized后面括号里是类,此时,线程获得的是对象锁.例如:

  class ArrayWithLockOrder{
  private static long num_locks = 0;
  private long lock_order;
  private int[] arr;

  public ArrayWithLockOrder(int[] a)
  {
    arr = a;
    synchronized(ArrayWithLockOrder.class) {//-----这里
      num_locks++;             // 锁数加 1。


 

察看评论详细内容 我要发表评论
作者笔名简短内容 发表时间
:

键盘也能翻页,试试“← →”键

相关文章

关注我们

最新资讯离线随时看 聊天吐槽赢奖品