JAVA multithreading-lock Lock
Lock is an interface under the JUC package. The Lock interface is a tool for controlling multiple threads to access shared resources. Only one thread can acquire the lock of the Lock object at a time, and the thread should acquire the Lock object before accessing shared resources.
No lock, thread insecure
package com.peng.lock;
import java.util.concurrent.locks.ReentrantLock;
//测试lock锁
public class TestLock {
public static void main(String[] args) {
TestLock2 testLock2 = new TestLock2();
new Thread(testLock2).start();
new Thread(testLock2).start();
new Thread(testLock2).start();
}
}
class TestLock2 implements Runnable{
int ticketNums = 10;
@Override
public void run() {
while (true){
if (ticketNums>0){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(ticketNums--);
}else {
break;
}
}
}
}
After adding the lock, concurrent programming is realized
package com.peng.lock;
import java.util.concurrent.locks.ReentrantLock;
//测试lock锁
public class TestLock {
public static void main(String[] args) {
TestLock2 testLock2 = new TestLock2();
new Thread(testLock2).start();
new Thread(testLock2).start();
new Thread(testLock2).start();
}
}
class TestLock2 implements Runnable{
int ticketNums = 10;
// 定义lock锁 ReentrantLock是Lock接口的实现类
private final ReentrantLock lock = new ReentrantLock();
@Override
public void run() {
while (true){
try{
//加锁,在要变化的量加锁
lock.lock();
if (ticketNums>0){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(ticketNums--);
}else {
break;
}
}finally {
//解锁 把解锁放在finally里
lock.unlock();
}
}
}
}
Comparison of synchronized and Lock
- Lock is a display lock that needs to be manually opened and closed. Synchronized is an implicit lock that is automatically released out of scope (scope: method or code block)
- Lock has only code block lock, synchronized has method lock and code block lock
- Using Lock locks, JVM will spend less time scheduling threads, with better performance, better scalability, and more subclasses (such as ReentrantLock)
Priority order: Loc>Synchronization code block (used in the method body, resources have been allocated)>Synchronization method (used outside the method body)