Java锁
1.1 公平锁与非公平锁
并发包中ReentrantLock的创建可以指定构造函数的boolean类型来得到公平锁或非公平锁,默认是非公平锁
关于两者区别:
公平锁:Threads acquire a fair lock in the order in which they requested it
公平锁,就是很公平,在并发环境中,每个线程在获取锁时会先查看此锁维护的等待队列,如果为空,活着当前线程时等待队列的第一个,就占有锁,否则就会加入到等待队列中,以后会按照FIFO的规则从队列中取到自己
非公平锁: a no fair lock permits barging: threads requesting a lock can jump ahead of the queue of waiting threads if the lock happens to be available when it is requested.
非公平锁比较粗鲁,上来就直接尝试占有锁,如果失败,就再采用类似公平锁那种方式
1.2 可重入锁(又名递归锁)
指的是同一线程外层函数获得锁之后,内层递归函数任然能获取该锁的代码,在同一线程在外层方法获取锁的时候,在进入内层方法会自动获取锁
也即是说,线程可以进入任何一个它已经拥有的锁所同步着的代码块。
可重入锁最大的作用就是避免死锁
synchronized 与ReentrantLock都是可重入锁
class Phone implements Runnable{
Lock lock = new ReentrantLock();
public synchronized void sendMsg(){
System.out.println(Thread.currentThread().getName()+" invoke sendMsg");
receiveMsg();
}
public synchronized void receiveMsg(){
System.out.println(Thread.currentThread().getName()+" invoke receiveMsg");
}
// 可重复加锁 必须加锁几次就需解锁几次
public void get(){
lock.lock();
lock.lock();
try{
System.out.println(Thread.currentThread().getName()+" invoke get");
set();
}finally {
lock.unlock();
lock.unlock();
}
}
public void set(){
lock.lock();
try{
System.out.println(Thread.currentThread().getName()+" invoke set");
}finally {
lock.unlock();
}
}
@Override
public void run() {
get();
}
}
public class ReenterLockDemo {
public static void main(String[] args) throws InterruptedException {
Phone phone = new Phone();
new Thread(()->{
phone.sendMsg();
},"t1").start();
new Thread(()->{
phone.sendMsg();
},"t2").start();
Thread.sleep(2000);
System.out.println("=============");
Thread t3 = new Thread(phone);
Thread t4 = new Thread(phone);
t3.start();
t4.start();
}
}
//运行结果
//t1 invoke sendMsg
//t1 invoke receiveMsg
//t2 invoke sendMsg
//t2 invoke receiveMsg
//=============
//Thread-0 invoke get
//Thread-0 invoke set
//Thread-1 invoke get
//Thread-1 invoke set
1.3 自旋锁
是指尝试获取锁的线程不会立即阻塞,而是采用循环的方式去尝试获取锁,这样的好处是减少线程上下文切换的消耗,缺点是循坏会消耗CPU
public class SpinLockDemo {
AtomicReference<Thread> atomicReference = new AtomicReference<>();
public void myLock(){
System.out.println(Thread.currentThread().getName()+" invoked myLock()");
while (!atomicReference.compareAndSet(null,Thread.currentThread())){}
}
public void myUnlock(){
System.out.println(Thread.currentThread().getName()+" invoked myUnlock()");
atomicReference.compareAndSet(Thread.currentThread(),null);
}
public static void main(String[] args) {
SpinLockDemo spinLockDemo = new SpinLockDemo();
new Thread(()->{
spinLockDemo.myLock();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
spinLockDemo.myUnlock();
},"t1").start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(()->{
spinLockDemo.myLock();
spinLockDemo.myUnlock();
},"t2").start();
}
}
//运行结果
//t1 invoked myLock()
//t2 invoked myLock()
//t1 invoked myUnlock()
//t2 invoked myUnlock()
1.4 读写锁
多个线程同时读一个资源类没有任何问题,所以为了满足并发量,读取共享资源应该可以同时进行
如果有一个线程想去写共享资源来,就不应该有其他线程可以对该资源进行读或写
读读能共存 、读写不能共存、 写写不能共存
写操作:原子+独占,整个过程必须是一个完整的统一体,中间不许被分割,被打断
class MyCache{
private volatile Map<String,Object> map = new HashMap<>();
private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
public void put(String key,Object value){
readWriteLock.writeLock().lock();
try {
System.out.println(Thread.currentThread().getName()+" 写入中");
try { Thread.sleep(300); }catch (Exception ignored){}
map.put(key,value);
System.out.println(Thread.currentThread().getName()+" 写入完成:");
}finally {
readWriteLock.writeLock().unlock();
}
}
public void get(String key) {
readWriteLock.readLock().lock();
try {
System.out.println(Thread.currentThread().getName()+" 读取中");
try { Thread.sleep(300); }catch (Exception ignored){}
Object o = map.get(key);
System.out.println(Thread.currentThread().getName()+" 读取完成:"+o);
}finally {
readWriteLock.readLock().lock();
}
}
}
public class ReadWriteLockDemo {
public static void main(String[] args) {
MyCache myCache = new MyCache();
for (int i = 0; i < 5; i++) {
final int temp = i;
new Thread(()->{
myCache.put(temp+"",temp+"");
},i+"").start();
}
for (int i = 0; i < 5; i++) {
final int temp = i;
new Thread(()->{
myCache.get(temp+"");
},i+"").start();
}
}
}
/*
未加锁运行
0 写入中
3 写入中
2 写入中
1 写入中
4 写入中
0 读取中
1 读取中
2 读取中
3 读取中
4 读取中
4 写入完成:
3 写入完成:
2 写入完成:
2 读取完成:null
3 读取完成:3
1 写入完成:
1 读取完成:null
0 写入完成:
0 读取完成:null
4 读取完成:null
加锁后运行
0 写入中
0 写入完成:
1 写入中
1 写入完成:
2 写入中
2 写入完成:
3 写入中
3 写入完成:
4 写入中
4 写入完成:
0 读取中
1 读取中
2 读取中
4 读取中
3 读取中
4 读取完成:4
3 读取完成:3
0 读取完成:0
2 读取完成:2
1 读取完成:1 */