Lock与synchronized的区别
synchronized是属于jvm层面的,如果遇到异常,jvm会自动释放锁.lock锁的释放是需要程序员操作,如果不释放就会产生死锁
在竞争不激烈的情况下,偶尔会有同步的情况发生,如果用synchronized会好一点,如果竞争很激烈的情况下,使用reentrantLock会好一点.
package org.fkjava.oa.base; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class Chen{ Lock lock = new ReentrantLock(); public void f(){ try { lock.lock(); for(int i=0;i<5;i++){ System.out.println("f(),i=" + i); Thread.currentThread().sleep(1000); } } catch (Exception e) { // TODO: handle exception }finally{ lock.unlock(); } } public void g(){ try { lock.lock(); for(int i=0;i<5;i++){ System.out.println("g(),i=" + i); Thread.currentThread().sleep(1000); } } catch (Exception e) { // TODO: handle exception }finally{ lock.unlock(); } } public static void main(String[] args) { final Chen c = new Chen(); new Thread(){ @Override public void run() { c.f(); } }.start(); new Thread(){ @Override public void run() { c.g(); } }.start(); } }