lock.lock(); 起始 lock.unlock(); 结尾
Lock 相当于 synchronized
Lock 对比 synchronized 更灵活, 可以锁随意的代码行
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class Service {
private final Lock lock = new ReentrantLock();
public void methodLock() {
try {
lock.lock();
System.out.print ("start methodLock -- " + "--" + Thread.currentThread().getName());
System.out.println(" end methodLock -- " + System.currentTimeMillis() + "--" + Thread.currentThread().getName());
lock.unlock();
// 其他业务代码
} catch (Exception e) {
e.printStackTrace();
}
}
}
class ThreadOne extends Thread {
private Service service;
public ThreadOne(Service service) {
this.service = service;
}
@Override
public void run() {
service.methodLock();
}
}
class ThreadTwo extends Thread {
private Service service;
public ThreadTwo(Service service) {
this.service = service;
}
@Override
public void run() {
service.methodLock();
}
}
class Run {
public static void main(String[] args) throws Exception {
Service service = new Service();
for (int i = 0; i < 5; i++) {
ThreadOne threadOne = new ThreadOne(service);
threadOne.start();
ThreadTwo threadTwo = new ThreadTwo(service);
threadTwo.start();
}
}
}