JAVA并发编程6

Posted Gggoblin

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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()+"读操作完毕");
}
}





























































以上是关于JAVA并发编程6的主要内容,如果未能解决你的问题,请参考以下文章

Java并发编程学习6-同步容器类和并发容器

Java并发编程学习6-同步工具类和并发容器

Java并发编程从入门到精通 - 第6章:线程池

6.并发编程--volatile

Java并发编程的艺术,解读并发编程的优缺点

Java并发编程的艺术,解读并发编程的优缺点