---
title: "怎样证明HashMap不是线程安全的"
author: "button"
date: "2014-04-03T09:57:08Z"
tags: []
categories: ["编程语言"]
slug: "hashmap"
draft: false
lastmod: "2014-04-03T09:57:08Z"
id: 2040340
url: "https://jic.iteye.com/blog/2040340"
---

HashMap用在方法内部并且不传到方法外面可以用HashMap,如果HashMap作为类的成员变量或静态属性

要为HashMap加线程安全锁Collections.synchronizedMap(new HashMap());

import java.util.Collections;

import java.util.HashMap;

import java.util.Map;

 

public class Test {

 

public static final Map&lt;String, String&gt; hashMap = Collections.synchronizedMap(new HashMap&lt;String, String&gt;());

 

public static void main(String\[] args) throws InterruptedException {

// 线程一

Thread t1 = new Thread() {

public void run() {

for (int i = 0; i &lt; 25; i++) {

hashMap.put(String.valueOf(i), String.valueOf(i));

}

}

};

 

 

Thread t2 = new Thread() {

public void run() {

for (int j = 25; j &lt; 50; j++) {

hashMap.put(String.valueOf(j), String.valueOf(j));

}

}

};

 

t1.start();

t2.start();

 

// 主线程休眠1秒钟

Thread.currentThread().sleep(1000);

 

System.out.println("size---" + hashMap.size());

for (int l = 0; l &lt; 50; l++) {

System.err.println(String.valueOf(l) + ":" + hashMap.get(String.valueOf(l)));

}

 

}

 

}