【Java】synchronized

synchronized
代表这个方法加锁,相当于不管哪一个线程(例如线程A),运行到这个方法时,都要检查有没有其它线程B(或者C、 D等)正在用这个方法(或者该类的其他同步方法),有的话要等正在使用synchronized方法的线程B(或者C 、D)运行完这个方法后再运行此线程A,没有的话,锁定调用者,然后直接运行。它包括两种用法:synchronized 方法和 synchronized 块。

例如:

public synchronized void synMethod(){
//方法体
}
public Object synMethod(Object a1){
    synchronized(a1){
//一次只能有一个线程进入
  }
}
public classMyThread implements Runnable{
    public static void main(Stringargs[]){
      MyThread mt=new MyThread();
        Thread t1=newThread(mt,"t1");
        Thread t2=newThread(mt,"t2");
        Thread t3=newThread(mt,"t3");
        Thread t4=newThread(mt,"t4");
        Thread t5=newThread(mt,"t5");
        Thread t6=newThread(mt,"t6");
        t1.start();
        t2.start();
        t3.start();
        t4.start();
        t5.start();
        t6.start();
}   
public void run(){
    synchronized(this){
      System.out.println(Thread.currentThread().getName());
   }
}

《2》
class FineGrainLock{
 MyMemberClassx,y;
 Object xlock = new Object(), ylock = newObject();
 public void foo(){
     synchronized(xlock){
     //accessxhere
      }
     //dosomethinghere-butdon'tusesharedresources
      synchronized(ylock){
      //accessyhere
      }
 }
    public void bar(){
      synchronized(this){
         //accessbothxandyhere
     }
    //dosomethinghere-butdon'tusesharedresources
    }
}

classArrayWithLockOrder{
 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。
           lock_order=num_locks;//为此对象实例设置唯一的lock_order。
      }
 }
 publiclonglockOrder(){
      returnlock_order;
 }
 public int[] array(){
     return arr;
 }
}
class SomeClass implements Runnable{
 public int sumArrays(ArrayWithLockOrdera1,ArrayWithLockOrdera2){
      intvalue=0;
      ArrayWithLockOrderfirst=a1;//保留数组引用的一个
     ArrayWithLockOrderlast=a2;//本地副本。
     intsize=a1.array().length;
      if(size==a2.array().length){
         if(a1.lockOrder()>a2.lockOrder()){//确定并设置对象的锁定顺序。
             first=a2;
            last=a1;
           }
         synchronized(first){//按正确的顺序锁定对象。
             synchronized(last){
                 int[]arr1=a1.array();
                 int[]arr2=a2.array();
                 for(int i=0;i<size;i++)
                       value+=arr1[i]+arr2[i];
               }
          }
     }
 return value;
 }
 public void run(){
 //
 }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值