正常使用lock.lock()和lock.unlock() ,Lock会发生死锁现象,所以要放在finally中
public class LockTest {
Lock lock = new ReentrantLock();
private ArrayList<Integer> arrayList = new ArrayList<Integer>();
public static void main(String[] args) {
final LockTest test = new LockTest();
new Thread("线程一"){
public void run() {
test.insert(Thread.currentThread());
}
}.start();
new Thread("线程二"){
public void run() {
test.insert(Thread.currentThread());
}
}.start();
}
public void insert(Thread thread) {
lock.lock();
try {
System.out.println(thread.getName()+"得到了锁");
for(int i=0;i<5;i++) {
arrayList.add(i);
}
} catch (Exception e) {
// TODO: handle exception
}finally {
System.out.println(thread.getName()+"释放了锁");
System.out.println("arrayList is:" + arrayList);
lock.unlock();
}
}
}