1:lock和synchronized对比
2.读写锁:ReadWriteLock
3.用写锁实现库存递减
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class ReadWriteLockTest {
public static boolean flag = true;
public static void main(String[] args) {
final Queue3 q3 = new Queue3();
for (int i = 0; i < 3; i++) {
new Thread() {
public void run() {
while (ReadWriteLockTest.flag) {
q3.put();
}
}
}.start();
}
}
}
class Queue3 {
private Integer data = 10;// 共享数据,只能有一个线程能写该数据,但可以有多个线程同时读该数据。
final ReadWriteLock lock = new ReentrantReadWriteLock();
public void put() {
lock.writeLock().lock();// 写锁开启,这时只有一个写线程进入
try {
System.out.println(Thread.currentThread().getName() + " have write data: " + data);
if (data == 0) {
ReadWriteLockTest.flag = false;
return;
}
data--;
} finally {
lock.writeLock().unlock();
}
}
}
4.用读写锁实现一个简单缓存机制