多线程hashmap死循环
时间: 2023-12-17 15:28:39 浏览: 26
多线程环境下,如果使用非线程安全的HashMap,可能会导致死循环的问题。这是因为多个线程同时对HashMap进行操作,可能会导致HashMap的内部数据结构被破坏,从而导致get()方法陷入死循环。解决这个问题的方法是使用线程安全的ConcurrentHashMap代替HashMap。ConcurrentHashMap使用了分段锁的机制,可以保证在多线程环境下的线程安全性。
以下是使用ConcurrentHashMap的示例代码:
```java
import java.util.concurrent.ConcurrentHashMap;
public class MyThread implements Runnable {
private ConcurrentHashMap<String, Integer> map;
public MyThread(ConcurrentHashMap<String, Integer> map) {
this.map = map;
}
public void run() {
for (int i = 0; i < 100000; i++) {
map.put(Thread.currentThread().getName() + "-" + i, i);
}
}
public static void main(String[] args) throws InterruptedException {
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<String, Integer>();
Thread t1 = new Thread(new MyThread(map));
Thread t2 = new Thread(new MyThread(map));
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(map.size());
}
}
```