您的位置:首页 > 编程语言 > Java开发

java ReentrantLock重入锁的实现

2016-06-20 11:03 495 查看
最近正好空,研究了下JAVA并发包,具体大致如下

import java.util.ArrayList;

import java.util.concurrent.locks.Lock;

import java.util.concurrent.locks.ReentrantLock;

public class Test {
private ArrayList arrayList = new ArrayList();
public static Lock lock = new ReentrantLock(); 
public static Lock lock1 = new ReentrantLock(); 

public static void main(String[] args) {
final Test test = new Test();
final ArrayList arr = new ArrayList();
arr.add("a");
arr.add("b");
arr.add("c");
arr.add("d");
arr.add("e");
new Thread() {
public void run() {
test.delete(Thread.currentThread());
};
}.start();

new Thread() {
public void run() {
test.insert(Thread.currentThread(), arr);
};
}.start();
}

public void insert(Thread thread,ArrayList arr) {

// if (lock.tryLock()) {
try {
lock.lock();
System.out.println(thread.getName() + "得到了锁");
// Thread.sleep(5000);
for (int i = 0; i < 5; i++) {
if(i==3){
Thread.sleep(1000);
}
arrayList.add(arr.get(i).toString());
}
for (int j = 0; j < arrayList.size(); j++) {
System.out.println(thread.getName() + ":"
+ arrayList.get(j).toString() + "length:"
+ arrayList.size());
}
} catch (Exception e) {
// TODO: handle exception
} finally {
System.out.println(thread.getName() + "释放了锁");
lock.unlock();
}
// }

}

public void delete(Thread thread) {
//
// if (lock.tryLock()) {
try {
lock1.lock();
System.out.println(thread.getName() + "得到了锁1");
if(arrayList.size()<1){
Thread.sleep(1000);//防止arrayList为空
System.out.println(arrayList.get(0).toString());
arrayList.remove(0);
}

for (int i = 0; i < 10; i++) {
if (i == 8) {
System.out.println("ok");
}
}
} catch (Exception e) {
System.out.print("报错了");
// TODO: handle exception
} finally {
System.out.println(thread.getName() + "释放了锁1");
lock1.unlock();
}
}

// }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息