考虑一个场景,轮流打印0-100之内的技术和偶数。经过使用 synchronize 的 wait,notify机制就能够实现,核心思路以下:
使用两个线程,一个打印奇数,一个打印偶数。这两个线程会共享一个数据,数据每次自增,当打印奇数的线程发现当前要打印的数字不是奇数时,执行等待,不然打印奇数,并将数字自增1,对于打印偶数的线程也是如此java
//打印奇数的线程 private static class OldRunner implements Runnable{ private MyNumber n; public OldRunner(MyNumber n) { this.n = n; } public void run() { while (true){ n.waitToOld(); //等待数据变成奇数 System.out.println("old:" + n.getVal()); n.increase(); if (n.getVal()>98){ break; } } } } //打印偶数的线程 private static class EvenRunner implements Runnable{ private MyNumber n; public EvenRunner(MyNumber n) { this.n = n; } public void run() { while (true){ n.waitToEven(); //等待数据变成偶数 System.out.println("even:"+n.getVal()); n.increase(); if (n.getVal()>99){ break; } } } }
共享的数据以下ui
private static class MyNumber{ private int val; public MyNumber(int val) { this.val = val; } public int getVal() { return val; } public synchronized void increase(){ val++; notify(); //数据变了,唤醒另外的线程 } public synchronized void waitToOld(){ while ((val % 2)==0){ try { System.out.println("i am "+Thread.currentThread().getName()+" ,but now is even:"+val+",so wait"); wait(); //只要是偶数,一直等待 } catch (InterruptedException e) { e.printStackTrace(); } } } public synchronized void waitToEven(){ while ((val % 2)!=0){ try { System.out.println("i am "+Thread.currentThread().getName()+" ,but now old:"+val+",so wait"); wait(); //只要是奇数,一直等待 } catch (InterruptedException e) { e.printStackTrace(); } } } }
运行代码以下this
MyNumber n = new MyNumber(0); Thread old=new Thread(new OldRunner(n),"old-thread"); Thread even = new Thread(new EvenRunner(n),"even-thread"); old.start(); even.start();
运行结果以下spa
i am old-thread ,but now is even:0,so wait even:0 i am even-thread ,but now old:1,so wait old:1 i am old-thread ,but now is even:2,so wait even:2 i am even-thread ,but now old:3,so wait old:3 i am old-thread ,but now is even:4,so wait even:4 i am even-thread ,but now old:5,so wait old:5 i am old-thread ,but now is even:6,so wait even:6 i am even-thread ,but now old:7,so wait old:7 i am old-thread ,but now is even:8,so wait even:8
上述方法使用的是 synchronize的 wait notify机制,一样可使用显示锁来实现,两个打印的线程仍是同一个线程,只是使用的是显示锁来控制等待事件操作系统
private static class MyNumber{ private Lock lock = new ReentrantLock(); private Condition condition = lock.newCondition(); private int val; public MyNumber(int val) { this.val = val; } public int getVal() { return val; } public void increase(){ lock.lock(); try { val++; condition.signalAll(); //通知线程 }finally { lock.unlock(); } } public void waitToOld(){ lock.lock(); try{ while ((val % 2)==0){ try { System.out.println("i am should print old ,but now is even:"+val+",so wait"); condition.await(); } catch (InterruptedException e) { e.printStackTrace(); } } }finally { lock.unlock(); } } public void waitToEven(){ lock.lock(); //显示的锁定 try{ while ((val % 2)!=0){ try { System.out.println("i am should print even ,but now old:"+val+",so wait"); condition.await();//执行等待 } catch (InterruptedException e) { e.printStackTrace(); } } }finally { lock.unlock(); //显示的释放 } } }
一样能够获得上述的效果线程
显示锁在java中经过接口Lock提供以下功能code
接口Condition把Object的监视器方法wait和notify分离出来,使得一个对象能够有多个等待的条件来执行等待,配合Lock的newCondition来实现。对象
从源码中能够看到,ReentrantLock的全部实现全都依赖于内部类Sync和ConditionObject。
Sync自己是个抽象类,负责手动lock和unlock,ConditionObject则实如今父类AbstractOwnableSynchronizer中,负责await与signal
Sync的继承结构以下继承
Sync的两个实现类,公平锁和非公平锁接口
公平的锁会把权限给等待时间最长的线程来执行,非公平则获取执行权限的线程与线程自己的等待时间无关
默认初始化ReentrantLock使用的是非公平锁,固然能够经过指定参数来使用公平锁
public ReentrantLock() { sync = new NonfairSync(); }
当执行获取锁时,实际就是去执行 Sync 的lock操做:
public void lock() { sync.lock(); }
对应在不一样的锁机制中有不一样的实现
公平锁实现
final void lock() { acquire(1); }
非公平锁实现
final void lock() { if (compareAndSetState(0, 1)) //先看当前锁是否是已经被占有了,若是没有,就直接将当前线程设置为占有的线程 setExclusiveOwnerThread(Thread.currentThread()); else acquire(1); //锁已经被占有的状况下,尝试获取 }
两者都调用父类AbstractQueuedSynchronizer的方法
public final void acquire(int arg) { if (!tryAcquire(arg) && acquireQueued(addWaiter(Node.EXCLUSIVE), arg)) //一旦抢失败,就会进入队列,进入队列后则是依据FIFO的原则来执行唤醒 selfInterrupt(); }
当执行unlock时,对应方法在父类AbstractQueuedSynchronizer中
public final boolean release(int arg) { if (tryRelease(arg)) { Node h = head; if (h != null && h.waitStatus != 0) unparkSuccessor(h); return true; } return false; }
公平锁和非公平锁则分别对获取锁的方式tryAcquire
作了实现,而tryRelease的实现机制则都是同样的
源码以下
protected final boolean tryAcquire(int acquires) { final Thread current = Thread.currentThread(); int c = getState(); //获取当前的同步状态 if (c == 0) { //等于0 表示没有被其它线程获取过锁 if (!hasQueuedPredecessors() && compareAndSetState(0, acquires)) { //hasQueuedPredecessors 判断在当前线程的前面是否是还有其它的线程,若是有,也就是锁sync上有一个等待的线程,那么它不能获取锁,这意味着,只有等待时间最长的线程可以获取锁,这就是是公平性的体现 //compareAndSetState 看当前在内存中存储的值是否是真的是0,若是是0就设置成accquires的取值。对于JAVA,这种须要直接操做内存的操做是经过unsafe来完成,具体的实现机制则依赖于操做系统。 //存储获取当前锁的线程 setExclusiveOwnerThread(current); return true; } } else if (current == getExclusiveOwnerThread()) { //判断是否是当前线程获取的锁 int nextc = c + acquires; if (nextc < 0)//一个线程可以获取同一个锁的次数是有限制的,就是int的最大值 throw new Error("Maximum lock count exceeded"); setState(nextc); //在当前的基础上再增长一次锁被持有的次数 return true; } //锁被其它线程持有,获取失败 return false; }
获取的关键实现为nonfairTryAcquire
,源码以下
final boolean nonfairTryAcquire(int acquires) { final Thread current = Thread.currentThread(); int c = getState(); if (c == 0) { //锁没有被持有 //能够看到这里会无视sync queue中是否有其它线程,只要执行到了当前线程,就会去获取锁 if (compareAndSetState(0, acquires)) { setExclusiveOwnerThread(current); //在判断一次是否是锁没有被占有,没有就去标记当前线程拥有这个锁了 return true; } } else if (current == getExclusiveOwnerThread()) { int nextc = c + acquires; if (nextc < 0) // overflow throw new Error("Maximum lock count exceeded"); setState(nextc);//若是当前线程已经占有过,增长占有的次数 return true; } return false; }
protected final boolean tryRelease(int releases) { int c = getState() - releases; if (Thread.currentThread() != getExclusiveOwnerThread()) //只能是线程拥有这释放 throw new IllegalMonitorStateException(); boolean free = false; if (c == 0) { //当占有次数为0的时候,就认为全部的锁都释放完毕了 free = true; setExclusiveOwnerThread(null); } setState(c); //更新锁的状态 return free; }
从源码的实现能够看到
ReetrantLock自己对锁的持有是可重入的,同时是线程独占的
。ReentrantLock的tryLock()与tryLock(long timeout, TimeUnit unit):
public boolean tryLock() { //本质上就是执行一次非公平的抢锁 return sync.nonfairTryAcquire(1); }有时限的tryLock核心代码是
sync.tryAcquireNanos(1, unit.toNanos(timeout));
,因为有超时时间,它会直接放到等待队列中,他与后面要讲的AQS的lock原理中acquireQueued的区别在于park的时间是有限的,详见源码AbstractQueuedSynchronizer.doAcquireNanos
内置锁功能上有必定的局限性,它没法响应中断,不能设置等待的时间