1. lock And sychronized
用sychronized修饰的方法或者语句块在代码执行完之后锁自动释放,而用Lock需要我们手动释放锁,所以为了保证锁最终被释放(发生异常情况),要把互斥区放在try内,释放锁放在finally内。
sychronized demo
synchronized(this) { }
lock
Lock writeLock = lock.writeLock();
writeLock.lock();
System.out.println("ReadWriteLockTest to addValue: " + v + " "
+ System.currentTimeMillis());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
try {
// 做写的工作
this.value += v;
this.addtimes++;
} finally {
// 释放writeLock锁
writeLock.unlock();
}