public class TryLockTest {
Lock lock = new ReentrantLock();
private ArrayList<Integer> arrayList = new ArrayList<Integer>();
public static void main(String[] args) {
final TryLockTest test = new TryLockTest();
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) {
Boolean getLock = false;
int count = 0;
while (!getLock){
count++;
System.out.println("第" + count + "次尝试获取锁");
if(lock.tryLock()){
getLock = true;
System.out.println(thread.getName()+"得到了锁");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
for(int i=0;i<5;i++) {
arrayList.add(i);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
System.out.println(thread.getName()+"释放了锁");
System.out.println("arrayList is:" + arrayList);
lock.unlock();
}
}
}
}
}