了解这两个机制之前要先了解java的内存模型,详见我的另一篇文章java内存模型
简单的来说,synchronize是从jvm层面实现的,lock就是代码层面实现的
再输容易一点就是synchronize是机器控制的,lock就是你写的代码人控制的
直接看代码可能更直观一点
1,synchronize
public void test() { synchronized(this) { // todo your code } } 此时,其效果等同于 public synchronized void test() { // todo your code } 2,lock public class Consumer implements Runnable { private Lock lock; public Consumer(Lock lock) { this. lock = lock; } @Override public void run() { // TODO Auto-generated method stub int count = 10; while( count > 0 ) { try { lock.lock(); count --; System. out.print( "B"); } finally { lock.unlock(); //主动释放锁 try { Thread. sleep(91L); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }}public class Producer implements Runnable{ private Lock lock; public Producer(Lock lock) { this. lock = lock; } @Override public void run() { // TODO Auto-generated method stub int count = 10; while (count > 0) { try { lock.lock(); count --; System. out.print( "A"); } finally { lock.unlock(); try { Thread. sleep(90L); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }}
public class Test { public static void main(String[] args) { Lock lock = new ReentrantLock(); Consumer consumer = new Consumer(lock); Producer producer = new Producer(lock); new Thread(consumer).start(); new Thread( producer).start(); }}
在并发小的时候使用synchronize是不错的选择,因为jvm开销小,当并发大的时候就要用lock好好设计程序了!