多线程 (测试用例中用于测试单服务器高并发)
public class Test2 {
public static void main(String[] args) {
Cache1 c = new Cache1();
ExecutorService executorService = Executors.newCachedThreadPool();
for (int i = 0; i < 100; i++) {
int finalI = i;
executorService.execute(() -> {
try {
c.getData("1","1");
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
}
}
class Cache1 {
private ReadWriteLock rwl = new ReentrantReadWriteLock();
private Map<String, String> redisCache = new HashMap();
//高效率双重检测锁。
public Object getData(String key, String data) throws InterruptedException {
String value = redisCache.get(key);
//redis 热点问题
//服务器多线程并发访问时,可能会有多个线程同时访问为空,都会去执行设置操作,
if (value == null) {
//可能有多个线程阻塞在这里,当synchronized执行完成之后。
synchronized (this) {
value = redisCache.get(key);
//每个线程进入后,发现如果已经有值了,就不再执行set操作
if (value == null) {
System.out.println("读取数据库");
Thread.sleep(10);
value = data;
redisCache.put(key, value);
}else {
System.out.println("进入同步代码块 读取缓存");
}
}
}else {
System.out.println("读取缓存");
}
return value;
}
}
线程间通信:
public class TestThread {
public static void main(String[] args) {
Test1 t = new Test1();
new Thread(() -> {
for (int i = 0; i < 10; i++) {
t.one();
}
}).start();
new Thread(() -> {
for (int i = 0; i < 10; i++) {
t.two();
}
}).start();
}
}
// 代码间通信。
class Test1 {
boolean isOk;
public synchronized void one() {
while (!isOk) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int i = 0; i < 2; i++) {
System.out.println("one = " + i);
}
isOk = false;
this.notify();
}
public synchronized void two() {
while (isOk) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int i = 0; i < 4; i++) {
System.out.println("two ==== " + i);
}
isOk = true;
this.notify();
}
}