您的HashMap和ConcurrentHashMap在多线程环境中工作原因的原因是输入较少。我正在同时放置和读取200个键值对。
只需将ConcurrentHashMap替换为代码中的HashMap,您将获得concurrentModificationException。
ConcurrentHashMap实现:package com.java.ConcurrentHashMap;import java.util.HashMap;import java.util.HashSet;import java.util.Iterator;import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;public class ConcurrentHashMapDemo {
private final ConcurrentHashMap> studentsBySection = new ConcurrentHashMap<>();
public void addStudentToSection(Student student, Section sec) {//System.out.println(Thread.currentThread().getName());
Set students = studentsBySection.get(sec);
if (students == null) {
students = new HashSet<>();
studentsBySection.putIfAbsent(sec, students);
}
students.add(student);
}
public static void main(String[] args) {
ConcurrentHashMapDemo ob = new ConcurrentHashMapDemo();
Thread t1 = new Thread(ob.new WriteThreasOne());
t1.setName("one");
Thread t3 = new Thread(ob.new WriteThreasTwo());
t3.setName("three");
Thread t2= new Thread(ob.new ReadThread());
t2.setName("two");
t1.start();
t2.start();
t3.start();
}
class WriteThreasOne implements Runnable {
@Override
public void run() {
final Section A = new Section("A");
for(int i=0;i<100;i++) {
addStudentToSection(new Student("alex"+i),A);
}
}
}
class WriteThreasTwo implements Runnable {
@Override
public void run() {
final Section A = new Section("A");
for(int i=1;i<100;i++) {
addStudentToSection(new Student("sam"+i),A);
}
}
}
class ReadThread implements Runnable {
@Override
public void run() {
//System.out.println(Thread.currentThread().getName());
Iterator ite = studentsBySection.keySet().iterator();
while(ite.hasNext()){
Section key = ite.next();
System.out.println(key+" : " + studentsBySection.get(key));
}
}
} }
科类:package com.java.ConcurrentHashMap;public class Section {
public Section(String sectionName) {
this.sectionName = sectionName;
}
private String sectionName;
public String getSectionName() {
return sectionName;
}
public void setSectionName(String sectionName) {
this.sectionName = sectionName;
}
@Override
public String toString() {
return "Section [sectionName=" + sectionName + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((sectionName == null) ? 0 : sectionName.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Section other = (Section) obj;
if (sectionName == null) {
if (other.sectionName != null)
return false;
} else if (!sectionName.equals(other.sectionName))
return false;
return true;
}}
学生班:package com.java.ConcurrentHashMap;public class Student {
private String studName;
public Student(String studName) {
this.studName = studName;
}
public String getStudName() {
return studName;
}
public void setStudName(String studName) {
this.studName = studName;
}
@Override
public String toString() {
return "Student [ studName=" + studName + "]";
}}