volatile synchronized 性能比较测试,但结果与期望不符,请大神解惑

特拉仔 发布于 2016/12/24 12:04
阅读 259
收藏 0

在看“JAVA并发编程的艺术”,想测试一下VOLATILE和SYNCHRONIZED在性能上读写的优劣,不考虑最终读的结果。我认为VOLATILE应该会快,但结果缺相反,请大神帮我分析分析

package com.jv.parallel.compare;


import java.util.Date;


class Counter1{
private volatile long counter=0L;

public long calc(){
return counter++;
}

public long get(){
return counter;
}
}


public class VolatileSample {
public static void main(String[] args) {
final Counter2 cnt = new Counter2();
Thread tWrite = new Thread(new Runnable() {

@Override
public void run() {
long temp = 0L;
long start = new Date().getTime();
for(int i=0;i<100000000;i++){
temp = cnt.calc();
}
long end = new Date().getTime();
System.out.println("tWrite consume time:"+(end-start));
System.out.println("tWrite counter: "+temp);
}
});
Thread tRead = new Thread(new Runnable() {

@Override
public void run() {
long temp = 0L;
long start = new Date().getTime();
for(int i=0;i<100000000;i++){
temp = cnt.get();
}
long end = new Date().getTime();
System.out.println("tRead consume time:"+(end-start));
System.out.println("tRead counter: "+temp);
}
});

tWrite.start();
tRead.start();
}
}


package com.jv.parallel.compare;


import java.util.Date;


class Counter2{
private long counter=0L;

public synchronized long calc(){
return counter++;
}

public synchronized long get(){
return counter;
}
}


public class SynchornizedSample {
public static void main(String[] args) {
final Counter2 cnt = new Counter2();
Thread tWrite = new Thread(new Runnable() {

@Override
public void run() {
long temp = 0L;
long start = new Date().getTime();
for(int i=0;i<100000000;i++){
temp = cnt.calc();
}
long end = new Date().getTime();
System.out.println("tWrite consume time:"+(end-start));
System.out.println("tWrite counter: "+temp);
}
});
Thread tRead = new Thread(new Runnable() {

@Override
public void run() {
long temp = 0L;
long start = new Date().getTime();
for(int i=0;i<100000000;i++){
temp = cnt.get();
}
long end = new Date().getTime();
System.out.println("tRead consume time:"+(end-start));
System.out.println("tRead counter: "+temp);
}
});
tWrite.start();
tRead.start();
}
}

测试结果:

VOLATILE:

tRead consume time:6623
tRead counter: 58595620
tWrite consume time:7190
tWrite counter: 99999999


SYNCHRONIZED:
tRead consume time:4680
tRead counter: 50368613
tWrite consume time:5362
tWrite counter: 99999999


加载中
返回顶部
顶部