结论
先说结论:两者相差非常细微,synchronized偶尔表现稍微优秀一点点
两者之间的区别
两者间的区别大概有:
1、一个是jvm关键字,一个是java类
2、Lock接口提供更多可适配的类和方法,包含非公平锁、读写锁 这些synchronized都提供不了
3、synchronized不用处理异常情况下的锁释放
更多区别参见网友的帖子了, 有很多详细的解释,比如:https://blog.csdn.net/fxh13579/article/details/79044637/
运行对比:
synchronized:
50000 : 172
50000 : 187
50000 : 187
50000 : 172
50000 : 175
50000 : 187
50000 : 168
500000 : 629
500000 : 577
500000 : 571
500000 : 603
500000 : 562
500000 : 531
500000 : 547
5000000 : 5596
5000000 : 13327
5000000 : 7895
5000000 : 8220
9000000 : 18085
9000000 : 7300
9000000 : 13212
Lock:
50000 : 196
50000 : 172
50000 : 189
50000 : 219
50000 : 187
500000 : 765
500000 : 933
500000 : 802
500000 : 912
500000 : 765
5000000 : 8834
5000000 : 7361
5000000 : 8123
5000000 : 8010
5000000 : 8375
9000000 : 11697
9000000 : 17186
9000000 : 16770
赋上测试代码:
package cn.yonghui.microstore;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.springframework.scheduling.concurrent.CustomizableThreadFactory;
public class LockTest {
final static int count = 9000000;
final static CountDownLatch latch = new CountDownLatch(count);
// static AtomicInteger threadCount = new AtomicInteger(0);
static int threadCount = 0;
static Lock lock = new ReentrantLock();
public static void main(String[] args) throws Exception {
LockTest lt = new LockTest();
lt.r();
}
void r() throws InterruptedException {
BlockingQueue<Runnable> bq = new LinkedBlockingQueue<Runnable>(10000000);
ThreadPoolExecutor executor = new ThreadPoolExecutor(100, 5000, 300, TimeUnit.MICROSECONDS, bq, new CustomizableThreadFactory("x-"));
long t = System.currentTimeMillis();
for(int i = 0; i<count; i++) {
Mythread mt = new Mythread();
executor.execute(mt);
}
latch.await();
System.out.print(threadCount + " : ");
executor.shutdown();
System.out.println(System.currentTimeMillis() - t);
}
class Mythread extends Thread{
@Override
public void run() {
// syhc();
lock();
}
void lock() {
boolean l = false;
try {
l = lock.tryLock(5, TimeUnit.HOURS);
if(l) {
exe();
}
}catch(Exception e) {
e.printStackTrace();
}finally {
if(l) {
lock.unlock();
}
}
}
void syhc() {
synchronized(latch) {
exe();
}
}
void exe() {
long t = System.currentTimeMillis();
String str = "" + t;
byte[] secretBytes = null;
try {
secretBytes = MessageDigest.getInstance("md5").digest(str.getBytes());
// System.out.println(t + " : " + new String(secretBytes));
threadCount++;
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("没有这个md5算法!");
}
latch.countDown();
}
}
}