ReentrantLock分类FairSync公平锁 - 构造函数true - 线程轮流获得锁NonfairSync非公平锁 - 默认,构造函数false - 跟Synchronized一样是非公平
ReentrantLock
AbstractQueuedSynchronizer
NonfairSync
Sync
Sync
区别1. lockInterruptibly:等待获取锁的线程1,在此过程中,如果被其他线程nterrupt,则该线程1立刻直接不等待获取锁,丢弃锁,直接抛出异常2. lock:等待获取锁的线程1,在此过程中,如果被其他线程interrupt,则延迟到获取锁才interrupt
package top.linruchang.springdemo;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.locks.ReentrantLock;
/**
* 作用:
*
* @author LinRuChang
* @version 1.0
* @date 2021/03/14
* @since 1.8
**/
@Slf4j
public class OtherTest3 {
public static void main(String[] args) throws InterruptedException {
System.out.println("\n=========LockInterruptibly===========\n");
testLockInterruptibly();
Thread.sleep(15000);
System.out.println("\n==========Lock==========\n");
testLock();
}
public static void testLockInterruptibly() throws InterruptedException {
TestLock testLock = new TestLock();
Thread thread1 = new Thread(() -> {
testLock.testLockInterruptibly();
});
thread1.start();
Thread.sleep(500);
Thread thread2 = new Thread(() -> {
testLock.testLockInterruptibly();
});
thread2.start();
Thread.sleep(500);
log.info("中断第二个线程");
thread2.interrupt();
}
public static void testLock() throws InterruptedException {
TestLock testLock = new TestLock();
Thread thread1 = new Thread(() -> {
testLock.testLock();
});
thread1.start();
Thread.sleep(500);
Thread thread2 = new Thread(() -> {
testLock.testLock();
});
thread2.start();
Thread.sleep(500);
log.info("中断第二个线程");
thread2.interrupt();
}
}
@Slf4j
class TestLock {
ReentrantLock reentrantLock = new ReentrantLock();
public void testLockInterruptibly() {
String threadName = Thread.currentThread().getName();
log.info(threadName + "启动");
try {
//获取到锁,但可以调用interceprt使得锁失效
reentrantLock.lockInterruptibly();
log.info(threadName + ":休眠10s");
Thread.sleep(10000);
log.info(threadName + ":休眠起来啦");
} catch (Exception e) {
log.error(threadName + ":发生异常" + e);
} finally {
reentrantLock.unlock();
log.info(threadName + "结束,并释放锁");
}
}
public void testLock() {
String threadName = Thread.currentThread().getName();
log.info(threadName + "启动");
try {
//获取到锁,但可以调用interceprt使得锁失效
reentrantLock.lock();
log.info(threadName + ":第一个休眠10s");
try {
Thread.sleep(10000);
}catch (Exception e) {
log.error(threadName + ":发生异常【第一个休眠】" + e);
}
log.info(threadName + ":第一个休眠起来啦");
log.info(threadName + ":第二个休眠10s");
try {
Thread.sleep(10000);
}catch (Exception e) {
log.error(threadName + ":发生异常【第二个休眠】" + e);
}
log.info(threadName + ":第二个休眠起来啦");
} catch (Exception e) {
log.error(threadName + ":发生异常" + e);
} finally {
reentrantLock.unlock();
log.info(threadName + "结束,并释放锁");
}
}
}
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/weixin_39651356/article/details/114860108
内容来源于网络,如有侵权,请联系作者删除!