java并发之readlock writelock

package learnjson;


import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;


public class BigPlay01 {
//readlock writelock
public static void main(String[] args) {

final MyPlay myPlay=new MyPlay();
for (int i = 0; i < 2; i++) {
new Thread(){
public void run(){
myPlay.get();
}
}.start();
}

for (int i = 0; i < 2; i++) {
new Thread(){
public void run(){
myPlay.put();
}
}.start();
}

}


}
class MyPlay {
private final ReentrantReadWriteLock readWriteLock=new ReentrantReadWriteLock();




public void get(){
readWriteLock.readLock().lock();
try {
System.out.println(Thread.currentThread().getName()+" read start");
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName()+" read end");
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
finally {
readWriteLock.readLock().unlock();
}
}


public void put(){
readWriteLock.writeLock().lock();
try {


System.out.println(Thread.currentThread().getName()+" write start");
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName()+"write end ");
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}

finally {
readWriteLock.writeLock().unlock();
}
}

}

猜你喜欢

转载自blog.csdn.net/douyunqian668/article/details/80751928