java中hashtable和hashmap的区别我知道,就是有一点不太理解,线程安全和不安全好像没有实际区别啊?
hashtable是线程安全的,我开启多线程对同一个hashtable和hashmap读写,测试结果发现没什么区别。看不到实际的区别?谁能用简单的代码给我演示一下这两个在...
hashtable是线程安全的,我开启多线程对同一个hashtable和hashmap读写,测试结果发现没什么区别。看不到实际的区别?谁能用简单的代码给我演示一下这两个在线程方面安全性的区别?感激不尽啦!!!
展开
1个回答
展开全部
package test;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.concurrent.CountDownLatch;
public class HashTbAndHashMap {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
//testHashMap();
testHashTable();
}
}
public static void testHashMap() {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
int nbthread = 1000;
CountDownLatch countDownLatch = new CountDownLatch(nbthread);
for (int i = 0; i < nbthread; i++) {
Thread thread = new Thread(new MyThread(map, countDownLatch));
thread.start();
}
try {
countDownLatch.await();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(map.size());
}
public static void testHashTable() {
Hashtable<Integer, Integer> table = new Hashtable<Integer, Integer>();
int nbthread = 1000;
CountDownLatch countDownLatch = new CountDownLatch(nbthread);
for (int i = 0; i < nbthread; i++) {
Thread thread = new Thread(new MyThread(table, countDownLatch));
thread.start();
}
try {
countDownLatch.await();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(table.size());
}
}
=======================
package test;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.concurrent.CountDownLatch;
public class MyThread implements Runnable {
private HashMap<Integer, Integer> map;
private Hashtable<Integer, Integer> table;
private CountDownLatch countDownLatch;
public MyThread(HashMap<Integer, Integer> map, CountDownLatch countDownLatch) {
this.map = map;
this.countDownLatch = countDownLatch;
}
public MyThread(Hashtable<Integer, Integer> table,
CountDownLatch countDownLatch) {
this.table = table;
this.countDownLatch = countDownLatch;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
table.put(i, i);
//map.put(i, i);
}
countDownLatch.countDown();
}
}
你执行一下就看出来区别了
更多追问追答
追问
没看出来什么区别啊》??
hashmap一运行就直接报错了。
追答
run 里面 一个 是table 一个是map. 运行相应的test时候注意把前面的 // 去掉
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询