在java并发编程实战中说synchronized与ReentrantLock性能从java1.6以后基本持平,并且网上也有人这样说,然后我就用程序测试一下,测试环境jdk1.8 ,cpu i5-4210H,代码如下:
public class LockPerformanceTest {
static int threadCount = 8;
public static void main(String[] args) throws InterruptedException {
testReentrantLock();
Thread.sleep(1000);
testSynchronized();
}
private static void testSynchronized() {
List<Thread> threads = new ArrayList<>();
AtomicBoolean breakTag = new AtomicBoolean(false);
HashSet<String> set = new HashSet<String>();
final AtomicLong counter = new AtomicLong();
String val = "1";
for (int i = 0; i < threadCount; i++) {
Thread t = new Thread() {
public void run() {
this.setPriority(NORM_PRIORITY);
while (!breakTag.get()) {
synchronized (set) {
set.contains(val);
}
counter.incrementAndGet();
}
}
};
threads.add(t);
t.start();
}
Thread t= new Thread() {
public void run() {
this.setPriority(NORM_PRIORITY);
long lastCount = counter.get();
int loop = 0;
long total = 0;
while (true) {
long tempCount = counter.get() - lastCount;
total += tempCount;
lastCount = counter.get();
loop++;
if (loop >= 5) {
System.out
.println("Synchronized平均处理个数:" + total / loop);
breakTag.set(true);
break;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
threads.add(t);
t.start();
for(Thread th : threads){
try {
th.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private static void testReentrantLock() {
List<Thread> threads = new ArrayList<>();
AtomicBoolean breakTag = new AtomicBoolean(false);
HashSet<String> set = new HashSet<String>();
final AtomicLong counter = new AtomicLong();
ReentrantLock lock = new ReentrantLock();
String val = "1";
for (int i = 0; i < threadCount; i++) {
Thread t = new Thread() {
public void run() {
this.setPriority(NORM_PRIORITY);
while (!breakTag.get()) {
lock.lock();
try {
set.contains(val);
} finally {
lock.unlock();
}
counter.incrementAndGet();
}
}
};
threads.add(t);
t.start();
}
Thread t= new Thread() {
public void run() {
this.setPriority(NORM_PRIORITY);
long lastCount = counter.get();
int loop = 0;
long total = 0;
while (true) {
long tempCount = counter.get() - lastCount;
total += tempCount;
lastCount = counter.get();
loop++;
if (loop >= 5) {
System.out.println("ReentrantLock平均处理个数:" + total
/ loop);
breakTag.set(true);
break;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
threads.add(t);
t.start();
for(Thread th : threads){
try {
th.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
最后测试结果如下:在线程个数是1个的时候,性能差不多;2个时synchronized > ReentrantLock;2个以上ReentrantLock > synchronized,并且性能差距有0.5倍左右。所以在对性能要求不是很高的情况下还是用synchronized,毕竟使用方便,ReentrantLock在对性能有较高要求时使用,并且灵活性高,但是容易编程出错,万一忘了在finally中释放锁将造成死锁。