我有一个服务类,包含一个添加Student到a的方法Section。现在每个Section拥有set的Students与它相关联。此外,还有一个Map<Section, Set<Student>>定义两者之间的关系。在service看起来像这样与addStudent方法:public class MembershipService {private final Map<Section, Set<Student>> studentsBySection = new HashMap<>();public void addStudentToSection(Student student, Section sec) {
Set<Student> students = studentsBySection.get(sec);
if (students == null) {
students = new HashSet<>();
studentsBySection.put(sec, students);
}
students.add(student);}// ..... also containing helper method : getStudents(Section s)我需要在多线程场景中测试功能,我需要展示如果两个或多个线程试图从公共端添加或读取学生将会发生什么map。我清楚的知道,更换Hashmap与ConcurrentHashMap能解决我的目的,但我不能够证明确切行为。我的解决方案我创建了两个线程:Student1并Student2尝试将同一个Service实例传递给它们并执行添加。预期的行为hashmap应该ConcurrentModificationException和ConcurrentHashMap它一起不应该抛出。但它并没有表现出预期的行为,即使有了正常的工作HashMap。请指导。这是代码:Student1public class Student1 implements Runnable{Services services;public Student1(Services ser) {
this.services = ser;
new Thread(this, "Student 1").start();}@Overridepublic void run() {
final Student ALEX = new Student("alex");
services.getMembershipService().addStudentToSection(ALEX,services.getSection());;
try {
System.out.println("Student 1 sleeping");
Thread.sleep(100);
} catch (Exception e) {
System.out.println(e);
}}}STUDENT2 public class Student2 implements Runnable{Services services;public Student2(Services ser) {
this.services = ser;
new Thread(this, "Student 2").start();}@Overridepublic void run() {
final Student JOHN = new Student("john");
services.getMembershipService().addStudentToSection(JOHN,services.getSection());;}Tester.javapublic static void main(String[] args) {
final Services services = ServiceFactory.createServices();
final Section A = new Section("A");
services.createSection(A);
Student1 one = new Student1(services);
Student2 two = new Student2(services);}我如何证明我的案子?注意:这不是关于How ConcurrentHashMap works in java或多线程的。一般都知道。我只是无法将其与我的要求保持一致。
添加回答
举报
0/150
提交
取消