Java synchronized 与 lock (Reetrantlock)锁性能比较

使用synchronzied和ReetrantLock做一百万次自增运算性能比较,比较一个线程和多线程情况下

package com.lock.test;


public class LockValue implements Runnable{
private int value;
     public void run(){
    long time1=System.currentTimeMillis();
      for(int i=0;i<10000000;i++){
      increment();
      }
     
      long time2=System.currentTimeMillis();
      System.out.println("synchronized 100百万次运算耗时:"+(time2-time1));
     }


     public synchronized void increment(){
    value++;
     
     
     }




}

package com.lock.test;


import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;


public class LockValue1 implements Runnable{
private Lock lock=new ReentrantLock();
private Condition condition =lock.newCondition();
private int value;
     public void run(){
    long time1=System.currentTimeMillis();
   
      for(int i=0;i<10000000;i++){
      lock.lock();
increment();
lock.unlock();
       
      }
     
      long time2=System.currentTimeMillis();
      System.out.println("lock 100百万次运算耗时:"+(time2-time1));
     }


     public  void increment(){
    value++;
     
     
     }




}

package com.lock.test;


public class Maintest {
public static void main(String[] args) {
LockValue lockvalue=new LockValue();  
Thread[] arr=new Thread[10];
long time1=System.currentTimeMillis();
for(int i=0;i<10;i++){
Thread a=new Thread(lockvalue);
arr[i]=a;
a.start();
}
       
/* long time2=System.currentTimeMillis();
System.out.println("time2-time1:"+(time2-time1));
   LockValue1 lockvalue1=new LockValue1();
Thread[] brr=new Thread[10];
long time3=System.currentTimeMillis();
for(int i=0;i<10;i++){
Thread b=new Thread(lockvalue1);
brr[i]=b;
b.start();
}
long time4=System.currentTimeMillis();
System.out.println("time2-time1:"+(time4-time3));*/

}


}

Java synchronized 与 lock (Reetrantlock)锁性能比较_第1张图片

Java synchronized 与 lock (Reetrantlock)锁性能比较_第2张图片

单线程结果

Java synchronized 与 lock (Reetrantlock)锁性能比较_第3张图片

你可能感兴趣的:(java多线程)