package day2;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class Cache {
static Map<String, String> data = new HashMap<String, String>();
static ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
static Lock r = rwl.readLock();
static Lock w = rwl.writeLock();
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(5);
executor.execute(new WriterThread());
executor.execute(new ReadThread());
executor.execute(new WriterThread1());
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
executor.execute(new ReadThread1());
executor.shutdown();
}
static class ReadThread implements Runnable {
@Override
public void run() {
r.lock();
try {
String name = data.get("name");
System.out.println(name);
}finally {
r.unlock();
}
}
}
static class ReadThread1 implements Runnable {
@Override
public void run() {
r.lock();
try {
String name = data.get("name");
System.out.println(name);
}finally {
r.unlock();
}
}
}
static class WriterThread implements Runnable {
@Override
public void run() {
w.lock();
try {
data.put("name", "shidebin");
}finally {
w.unlock();
}
}
}
static class WriterThread1 implements Runnable {
@Override
public void run() {
w.lock();
try {
for(int i = 0;i<10;i++) {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("WriterThread1 is running");
data.put("name", "hahhhhhh");
}
}finally {
w.unlock();
}
}
}
}
console输出:
shidebin
WriterThread1 is running
WriterThread1 is running
WriterThread1 is running
WriterThread1 is running
WriterThread1 is running
WriterThread1 is running
WriterThread1 is running
WriterThread1 is running
WriterThread1 is running
WriterThread1 is running
hahhhhhh
写线程在运行时读线程和其他写线程都是堵塞的
本文通过一个使用ReentrantReadWriteLock实现的缓存示例,展示了多个读取线程与写入线程如何在Java中进行同步操作。该示例利用固定线程池启动了不同类型的线程,包括读取线程和写入线程,并使用读写锁来确保数据的一致性和并发访问时的性能。
298

被折叠的 条评论
为什么被折叠?



