Demo代码:
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* 读写操作类
*/
public class Demo {
private Map<String,Object> map = new HashMap<>();
//创建一个读写锁实例
private ReadWriteLock rw = new ReentrantReadWriteLock();
//创建一个读锁
private Lock r = rw.readLock();
//创建一个写锁
private Lock w = rw.writeLock();
/**
* 读操作
* @param key
* @return
*/
public Object get(String key) {
r.lock();
System.out.println(Thread.currentThread().getName() + "读操作开始执行......");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
return map.get(key);
} finally {
r.unlock();
System.out.println(Thread.currentThread().getName() + "读操作执行完成......");
}
}
/**
* 写操作
* @param key
* @param value
*/
public void put(String key,Object value) {
try {
w.lock();
System.out.println(Thread.currentThread().getName() + "写操作开始执行......");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
map.put(key, value);
} finally {
w.unlock();
System.out.println(Thread.currentThread().getName() + "写操作执行完成......");
}
}
}
main方法测试多线程写操作:
public class Main {
public static void main(String[] args) {
Demo d = new Demo();
new Thread(new Runnable() {
@Override
public void run() {
d.put("key1", "value1");
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
d.put("key2", "value1");
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
d.put("key3", "value1");
}
}).start();
}
}
结果:
Thread-0写操作开始执行......
Thread-0写操作执行完成......
Thread-1写操作开始执行......
Thread-1写操作执行完成......
Thread-2写操作开始执行......
Thread-2写操作执行完成......
结论:写操作之间是互斥的,不可以并发操作
main方法测试多线程读操作:
public class Main {
public static void main(String[] args) {
Demo d = new Demo();
d.put("key1", "value1");
new Thread(new Runnable() {
@Override
public void run() {
d.get("key1");
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
d.get("key1");
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
d.get("key1");
}
}).start();
}
}
结果:
main写操作开始执行......
main写操作执行完成......
Thread-0读操作开始执行......
Thread-1读操作开始执行......
Thread-2读操作开始执行......
Thread-0读操作执行完成......
Thread-1读操作执行完成......
Thread-2读操作执行完成......
结论:多线程读操作之间不是互斥的,可以并发操作
main方法测试多线程读写操作:
public class Main {
public static void main(String[] args) {
Demo d = new Demo();
new Thread(new Runnable() {
@Override
public void run() {
d.put("key1","value1");
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
System.out.println(d.get("key1"));
}
}).start();
}
}
结果:
Thread-0写操作开始执行......
Thread-0写操作执行完成......
Thread-1读操作开始执行......
Thread-1读操作执行完成......
value1
结论:多线程读写操作之间是互斥的