多个线程读写不能保证读写顺序。
class Dome {
public HashMap<String, Object> map = new HashMap<>();
public void put(String key, Object value) {
System.out.println(Thread.currentThread().getName() + "开始添加————————" + key);
map.put(key, value);
System.out.println(Thread.currentThread().getName() + "添加完成。。。。。。。。");
}
public Object get(String key) {
System.out.println(Thread.currentThread().getName() + "开始读取————————");
Object result = map.get(key);
System.out.println(Thread.currentThread().getName() + "读取完成————————");
return result;
}
}
public static void main(String[] args) {
Dome dome = new Dome();
for (int i = 0; i < 5; i++) {
final int temp = i;
new Thread(() -> {
dome.put(temp + "", temp);
}, "" + temp).start();
}
for (int i = 0; i < 5; i++) {
final int temp = i;
new Thread(() -> {
dome.get(temp + "");
}, "" + temp).start();
}
}
}
"
2开始添加————————2
0开始添加————————0
1开始读取————————
0开始读取————————
0读取完成————————
3开始添加————————3
3添加完成。。。。。。。。
2开始读取————————
2读取完成————————
4开始添加————————4
1开始添加————————1
1添加完成。。。。。。。。
4开始读取————————
4读取完成————————
3开始读取————————
3读取完成————————
4添加完成。。。。。。。。
1读取完成————————
0添加完成。。。。。。。。
2添加完成。。。。。。。。
加入读写锁后。
class Dome {
private volatile HashMap<String, Object> map = new HashMap<>();
private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
public void put(String key, Object value) {
lock.writeLock().lock();
try {
System.out.println(Thread.currentThread().getName() + "开始添加————————" + key);
map.put(key, value);
System.out.println(Thread.currentThread().getName() + "添加完成。。。。。。。。");
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.writeLock().unlock();
}
}
public void get(String key) {
lock.readLock().lock();
try {
System.out.println(Thread.currentThread().getName() + "开始读取————————");
Object result = map.get(key);
System.out.println(Thread.currentThread().getName() + "读取完成————————" + result);
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.readLock().unlock();
}
}
}
public static void main(String[] args) {
Dome dome = new Dome();
for (int i = 0; i < 5; i++) {
final int temp = i;
new Thread(() -> {
dome.put(temp + "", temp);
}, "" + temp).start();
}
for (int i = 0; i < 5; i++) {
final int temp = i;
new Thread(() -> {
dome.get(temp + "");
}, "" + temp).start();
}
}
}
0开始添加————————0
0添加完成。。。。。。。。
1开始添加————————1
1添加完成。。。。。。。。
3开始添加————————3
3添加完成。。。。。。。。
2开始添加————————2
2添加完成。。。。。。。。
4开始添加————————4
4添加完成。。。。。。。。
3开始读取————————
3读取完成————————3
2开始读取————————
0开始读取————————
1开始读取————————
4开始读取————————
4读取完成————————4
1读取完成————————1
0读取完成————————0
2读取完成————————2
Process finished with exit code 0