ConcurrentHashMap put
时间: 2023-10-15 12:25:39 浏览: 42
ConcurrentHashMap is a thread-safe implementation of the Java Map interface. It provides concurrent access and updates to its key-value pairs without the need for explicit locking. To put a key-value pair into a ConcurrentHashMap, you can use the `put()` method.
Here is an example of how to use the `put()` method in ConcurrentHashMap:
```java
import java.util.concurrent.ConcurrentHashMap;
public class Main {
public static void main(String[] args) {
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
// Put key-value pairs into the map
map.put("key1", 1);
map.put("key2", 2);
map.put("key3", 3);
System.out.println(map);
}
}
```
In this example, we create a ConcurrentHashMap and use the `put()` method to add key-value pairs. The keys are of type String and the values are of type Integer. After putting the key-value pairs, we print the map to see the contents.
The output will be something like:
```
{key1=1, key2=2, key3=3}
```
Note that ConcurrentHashMap allows multiple threads to access and modify the map concurrently, ensuring thread safety.