同步锁(Lock)
Lock机制提供了比synchronized代码块
和synchronized方法
更广泛的锁定操作,同步代码块和同步方法具有的功能Lock都有,除此之外更强大更体现面向对象。
下面代码使用Lock完成”吃苹果”的需求:
class Apple3 implements Runnable{
private int num = 500; //苹果总数
// 实例化一个Lock对象
private final Lock lock = new ReentrantLock();
@Override
public void run() {
for (int i=0;i<50;i++){
eat();
}
}
// 保证安全问题
private void eat(){
// 进入方法,立即加锁
lock.lock();
if (num>0){
try {
System.out.println(Thread.currentThread().getName()+"吃了编号为"+num+"的苹果");
Thread.sleep(10); // 此时是为了模拟网络延迟
num--;
}catch (Exception e){
e.printStackTrace();
}finally {
// 释放锁
lock.unlock();
}
}
}
}
public class Main {
public static void main(String[] args){
// 创建三个线程(同学)吃苹果
Apple3 a = new Apple3();
new Thread(a,"小A").start();
new Thread(a,"小B").start();
new Thread(a,"小C").start();
}
}