Java多线程进一步的理解------------实现读写锁
public class ReadAndWriteLock {
public static void main(String[] args) {
final QueueJ q = new QueueJ();
for (int i = 0; i <3 ; i++) {
new Thread(){
@Override
public void run() {
while (true) {
q.get();
}
}
}.start();
new Thread(){
@Override
public void run() {
q.put(new Random().nextInt(1000));
}
}.start();
}
}
}
class QueueJ {
private Object data = null;//共享数据,只能有一个线程
private ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
public void get() {
rwl.readLock().lock();
try {
System.out.println(Thread.currentThread().getName() + "will read");
Thread.sleep((long)(Math.random()*1000));
System.out.println(Thread.currentThread().getName() + "have read");
}catch (InterruptedException e) {
e.printStackTrace();
}finally {
rwl.readLock().unlock();
}
}
public void put(Object data) {
rwl.writeLock().lock();
try {
System.out.println(Thread.currentThread().getName() + "will write");
Thread.sleep((long)(Math.random()*1000));
this.data = data;
System.out.println(Thread.currentThread().getName() + "have write");
}catch (InterruptedException e){
e.printStackTrace();
}finally {
rwl.writeLock().unlock();
}
}
}
读之前,加上读锁,写之前加上写锁