通过Lock对象的lock()和unlock()方法来模拟synchronized待模块。
1.Lock lock = new ReentrantLock();
2.ReadWriterLock rwl = new ReentrantReadWriterLock();是用来维护读取与写入分离的lock,同时可以有多个线程持有readlock,因为read通常是安全的并发操作;但只有一个线程可以持有write lock。
(if a thread has a write lock,nobody can have read/write lock.)
入口类:
package thread.test05;
public class LockTest {
public static void main(String[] args) {
MyStack stack=new MyStack(20);
Thread t1=new MyThreadA(stack);
Thread t2=new MyThreadB(stack);
t1.start();
t2.start();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(stack);
}
}
class MyThreadA extends Thread{
private MyStack stack;
public MyThreadA (MyStack stack){
this.stack=stack;
}
public void run(){
for(int i=0;i<10;i++){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
stack.push(i+"");
}
}
}
class MyThreadB extends Thread{
private MyStack stack;
public MyThreadB (MyStack stack){
this.stack=stack;
}
public void run(){
for(int i=0;i<10;i++){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
stack.push((char)('A'+i)+"");
}
}
}
MyStack类如下:
package thread.test05;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class MyStack {
private Object[] data;
private int count;
private Lock lock;
public MyStack(int size){
data=new Object[size];
count=0;
lock=new ReentrantLock();
}
public void push(Object obj){
lock.lock();
try{
if(count==data.length){
throw new FullStackException("栈空间已满!");
}
data[count]=obj;
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
count++;
}
finally{
lock.unlock();
}
}
public String toString(){
StringBuffer sb=new StringBuffer();
for(int i=0;i<count;i++){
sb.append(data[i]+",");
}
return sb.toString();
}
}
经测试,MyStack中的数据不会发生混乱。
//
读写锁:
package thread.test05;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class LockTest2 {
private final ReadWriteLock rwl = new ReentrantReadWriteLock();
private final Lock r = rwl.readLock();
private final Lock w = rwl.writeLock();
}