Java synchronized 与 lock (Reetrantlock)锁性能比较
使用synchronzied和ReetrantLock做一百萬次自增運(yùn)算性能比較,比較一個線程和多線程情況下
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百萬次運(yùn)算耗時:"+(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百萬次運(yùn)算耗時:"+(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));*/
}
}
單線程結(jié)果
總結(jié)
以上是生活随笔為你收集整理的Java synchronized 与 lock (Reetrantlock)锁性能比较的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 交通警察设点查酒驾时一律设置必要的什么
- 下一篇: java重写paint方法时怎么样不覆盖