能用内置锁就用内置锁,不能用内置锁,才考虑用显示锁。
接口主要方法如下:
接口主要方法如下:
Lock lock = new ReentrantLock(); .... lock.lock();//获取锁 try{ //业务逻辑 }finally{ lock.unlock();//这边要注意释放,不然会导致锁泄露 }
public class LockDemo { Lock lock = new ReentrantLock(); static int num = 0; public void addNum(int value) { lock.lock(); try { int temp = num; num = num + value; Thread.sleep(100); System.out.println(value + "+" + temp + "=" + num); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } } static class AddThread1 extends Thread { LockDemo lockDemo; public AddThread1(LockDemo lockDemo) { this.lockDemo = lockDemo; } @Override public void run() { lockDemo.addNum(1); } } static class AddThread2 extends Thread { LockDemo lockDemo; public AddThread2(LockDemo lockDemo) { this.lockDemo = lockDemo; } @Override public void run() { lockDemo.addNum(2); } } public static void main(String[] args) { LockDemo lockDemo = new LockDemo(); AddThread1 addThread1 = new AddThread1(lockDemo); AddThread2 addThread2 = new AddThread2(lockDemo); addThread1.start(); addThread2.start(); } }
运行结果如下:
结果显示,跟之前synchronized结果是一样的,加锁解锁成功