一 简单锁
锁可以比 synchronized同步块更复杂,是同步块使用模式的一些封装,下面介绍一个简单的锁对象。
public class Lock {
/**
* 是否锁住
*/
private boolean isLocked = false;
/**
* 锁住
*
* @throws InterruptedException
*/
public synchronized void lock() throws InterruptedException {
while (isLocked) {
wait();
}
isLocked = true;
}
/**
* 解锁
*/
public synchronized void unlock() {
isLocked = false;
notify();
}
}
锁住lock, 如果已经被锁住了,要等待。 解锁unlock,通知唤醒一个等待对象。
二 无锁测试
public class CounterLock {
private Lock lock = new Lock();
private int count = 0;
public int inc() throws InterruptedException {
// lock.lock();
int newInt = ++count;
// lock.unlock();
return newInt;
}
public static void main(String[] args) {
final CounterLock counterLock = new CounterLock();
final CountDownLatch countDownLatch = new CountDownLatch(7);
for (int i = 0; i < 7; i++) {
new Thread() {
public void run() {
try {
System.out.println(counterLock.inc());
countDownLatch.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
}
try {
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
System.out.println(counterLock.inc());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private Lock lock = new Lock();
private int count = 0;
public int inc() throws InterruptedException {
// lock.lock();
int newInt = ++count;
// lock.unlock();
return newInt;
}
public static void main(String[] args) {
final CounterLock counterLock = new CounterLock();
final CountDownLatch countDownLatch = new CountDownLatch(7);
for (int i = 0; i < 7; i++) {
new Thread() {
public void run() {
try {
System.out.println(counterLock.inc());
countDownLatch.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
}
try {
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
System.out.println(counterLock.inc());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
打印的结果如下:
5
4
1
2
6
3
1
7
4
1
2
6
3
1
7
最终一行的结果,不一定是8,不能保证。 并且1出现了重复。
三 有锁测试
lock.lock();
int newInt = ++count;
lock.unlock();
return newInt;
}
测试结果,每行都不同,最终的值是 8, 如下
1
2
4
3
5
6
7
8