区别:
- synchronized是Java的关键字,而Lock是一个Java接口。
- synchronized无法判断是否获取到锁,而Lock可以。
- synchronized会自动释放锁(a 线程执行完同步代码会释放锁 ;b 线程执行过程中发生异常会释放锁),Lock需在finally中手工释放锁(unlock()方法释放锁),否则容易造成线程死锁;
- 用synchronized关键字的两个线程1和线程2,如果当前线程1获得锁,线程2线程等待。如果线程1阻塞,线程2则会一直等待下去,而Lock锁就不一定会等待下去,如果尝试获取不到锁,线程可以不用一直等待就结束了;
- synchronized的锁可重入、不可中断、非公平,而Lock锁可重入、可判断、可公平(两者皆可)
- Lock锁适合大量同步的代码的同步问题,synchronized锁适合代码少量的同步问题。
public class LockTest {
private Lock lock = new ReentrantLock();
public void lockTest(Thread thread) {
lock.lock();
try {
System.out.println("线程" + thread.getName() + "获取锁成功");
Thread.sleep(2000);
} catch (InterruptedException e) {
System.out.println("线程" + thread.getName() + "发生了异常释放锁");
} finally {
System.out.println("线程" + thread.getName() + "执行完毕释放锁");
lock.unlock();
}
}
public static void main(String[] args) {
LockTest lockTest = new LockTest();
int threadNum = 5;
CountDownLatch countDownLatch = new CountDownLatch(threadNum);
ExecutorService executorService = Executors.newCachedThreadPool();
for (int i = 0; i < threadNum; i++) {
executorService.execute(new Runnable() {
@Override
public void run() {
lockTest.lockTest(Thread.currentThread());
countDownLatch.countDown();
}
});
}
try {
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
executorService.shutdown();
}
}
//输出:
线程pool-1-thread-1获取锁成功
线程pool-1-thread-1执行完毕释放锁
线程pool-1-thread-3获取锁成功
线程pool-1-thread-3执行完毕释放锁
线程pool-1-thread-2获取锁成功
线程pool-1-thread-2执行完毕释放锁
线程pool-1-thread-4获取锁成功
线程pool-1-thread-4执行完毕释放锁
线程pool-1-thread-5获取锁成功
线程pool-1-thread-5执行完毕释放锁