java ReentrantLock重入锁的实现

来源:互联网 发布:ps软件百度云 编辑:程序博客网 时间:2024/06/06 04:51

最近正好空,研究了下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();
}
}


// }
}


0 0