Hashtable数据结构存储数据
与HashMap的比较
HashMap:线程不安全(多线程环境下可能会存在问题) Hashtable:多线程环境下,是安全的,在操作时,会使用synchronized将整张表锁起来,效率低下,例如一个添加方法 代码示例
package _线程工具类;
import java.util.Hashtable;
public class Main {
public static void main(String[] args) throws InterruptedException {
Hashtable<String, String> hm = new Hashtable<>();
//开启线程进行数据的添加,由于Hashtable是线程安全的
// 在添加时,会将表锁起来,就不会有其他线程对其影响
Thread t1 = new Thread(() -> {
for (int i = 0; i < 25; i++) {
hm.put(i + "", i + "");
}
});
//再开启一个线程添加数据
Thread t2 = new Thread(() -> {
for (int i = 25; i < 51; i++) {
hm.put(i + "", i + "");
}
});
//开启线程
t1.start();
t2.start();
System.out.println("----------------------------");
//为了t1和t2能把数据全部添加完毕,因为添加要时间,其是线程安全的,不允许同时线程1、2同时添加
Thread.sleep(1000);
//遍历数据,会看到其按顺序添加
for (int i = 0; i < hm.size(); i++) {
System.out.print(hm.get(i+"")+"\t");
}
}
}
ConcurrentHashMap集合
与HashMap、Hashtable比较
HashMap:是线程不安全的。多线程环境下会有数据安全问题 Hashtable:是线程安全的,但是会将整张表锁起来,效率低下 ConcurrentHashMap:也是线程安全的,效率较高。 在JDK7和JDK8中,底层原理不一样。 代码示例:
package _线程工具类;
import java.util.Hashtable;
import java.util.concurrent.ConcurrentHashMap;
public class Main {
public static void main(String[] args) throws InterruptedException {
ConcurrentHashMap<String, String> hm = new ConcurrentHashMap<>(100);
//开启线程进行数据的添加,由于Hashtable是线程安全的
// 在添加时,会将表锁起来,就不会有其他线程对其影响
Thread t1 = new Thread(() -> {
for (int i = 0; i < 25; i++) {
hm.put(i + "", i + "");
}
});
//再开启一个线程添加数据
Thread t2 = new Thread(() -> {
for (int i = 25; i < 51; i++) {
hm.put(i + "", i + "");
}
});
//开启线程
t1.start();
t2.start();
System.out.println("----------------------------");
//为了t1和t2能把数据全部添加完毕,因为添加要时间,其是线程安全的,不允许同时线程1、2同时添加
Thread.sleep(1000);
//遍历数据,会看到其按顺序添加
for (int i = 0; i < hm.size(); i++) {
System.out.print(hm.get(i+"")+"\t");
}
}
}
优点:线程安全,效率高。在操作时,会使用synchronized将整张表锁起来,保证线程安全