Sychronized不需要显示的获取、释放锁,简单
Lock需要显示地获取锁和释放锁,繁琐但能让代码更灵活
使用Lock需要显示地获取和释放锁,Synchronized不需要显示释放锁,实现简单
Lock可以实现锁的公平性,非阻塞获取锁,非中断获取锁
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Sequence {
private int value;
// 需要显示地获取锁和释放锁,繁琐但能让代码更灵活
// 使用Lock需要显示地获取和释放锁,Synchronized不需要显示释放锁,实现简单
// Lock可以实现锁的公平性,非阻塞获取锁,非中断获取锁
Lock lock = new ReentrantLock();
public int getNext(){
lock.lock();
int a= value++;
lock.unlock();
return a;
}
public static void main(String[] args) {
Sequence s = new Sequence();
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println(Thread.currentThread().getName()+" "+s.getNext());
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println(Thread.currentThread().getName()+" "+s.getNext());
}
}).start();
}
}
网友评论