JAVA并发编程6

说明:先上代码,笔记后续补充。
public class LockTest2 {
private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

public static void main(String[] args) {
final CountDownLatch latch = new CountDownLatch(2);
Long startTime = System.currentTimeMillis();
final LockTest2 test = new LockTest2();

Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
test.superGet(Thread.currentThread());
latch.countDown();
}
},"thread1");

Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
test.superGet(Thread.currentThread());
latch.countDown();
}
},"thread2");

thread1.start();
thread2.start();
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
long endTime = System.currentTimeMillis();
long result = endTime - startTime;
System.out.println("共耗时"+result);
}

//改良之后的get
private void superGet(Thread thread){
try {
lock.readLock().lock();
//lock.writeLock().lock(); 这个≈synchronized
long start = System.currentTimeMillis();
while (System.currentTimeMillis() - start <= 1){
System.out.println(thread.getName()+"正在执行读操作");
}
System.out.println(thread.getName()+"读操作完毕");
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.readLock().unlock();
}
}

private synchronized void get(Thread thread){
long start = System.currentTimeMillis();
while (System.currentTimeMillis() - start <= 1){
System.out.println(thread.getName()+"正在执行读操作");
}
System.out.println(thread.getName()+"读操作完毕");
}
}
posted @ 2018-04-22 22:23  Gggoblin  阅读(117)  评论(0编辑  收藏  举报