1、认识

2、优势
- Lock 类似于synchronized,具有相同的互斥性和内存可见性,但是更加灵活,加锁和放锁可以由使用者自己确定,Synchronized不需要显示地获取和释放锁,简单
- 可以方便的实行公平性
- 非阻塞的获取锁
- 能被中断的获取锁,synchronized锁可能出现异常而导致中断,无法释放锁,但是通过使用lock,可以直接将lock放在异常finally中,强制释放锁。
- 超时获取锁
3、使用
public class Sequence {
private int value ;
Lock lock = new ReentrantLock();
public int getNext() {
lock.lock();
int a = value++;
lock.unlock();
return a;
}
public static void main(String[] args) {
Sequence sequence = new Sequence();
new Thread(new Runnable() {
@Override
public void run() {
while(true) {
System.out.println(Thread.currentThread().getName()+" ----->"+sequence.getNext());
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
while(true) {
System.out.println(Thread.currentThread().getName()+" ----->"+sequence.getNext());
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
while(true) {
System.out.println(Thread.currentThread().getName()+" ----->"+sequence.getNext());
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
}
相关文章:
-
2021-06-01
-
2021-10-01
-
2022-12-23
-
2021-06-27
-
2021-12-19