代码如下:
1public class Lock { 2 private boolean isLocked = false; 3 4 public void lock() { 5 synchronized (this) { 6 while (isLocked) { 7 try { 8 wait(); 9 } catch (InterruptedException e) { 10 e.printStackTrace(); 11 isLocked = false; 12 break; 13 } 14 } 15 isLocked = true; 16 } 17 } 18 19 20 public void unLock() {//也可以把synchronized放在方法前 21 synchronized (this) { 22 isLocked = false; 23 notifyAll(); 24 } 25 } 26}
用法如下:
1public class Counter { 2 private int count = 0; 3 4 private Lock mLock = new Lock(); 5 6 public void inc(){ 7 mLock.lock(); 8 count++; 9 mLock.unLock(); 10 } 11 12 public int getCount(){ 13 return count; 14 } 15 16 public static void main(String[] args) throws InterruptedException { 17 18 Counter counter = new Counter(); 19 20 for (int i = 0; i < 500; i++) { 21 new Thread(new Runnable() { 22 @Override 23 public void run() { 24 25 try { 26 Thread.currentThread().sleep(100); 27 } catch (InterruptedException e) { 28 e.printStackTrace(); 29 } 30 counter.inc(); 31 } 32 }).start(); 33 } 34 35 36 Thread.currentThread().sleep(1000 * 5); 37 System.out.println("count=" + counter.getCount()); 38 } 39} 40
打印的结果如下:

