1、背景介绍
ArrayList、HashSet、HashMap等非线程安全类,如何在并发场景下使用呢?
2、Collections
Collections工具类,提供了几个方法,可以将非线程安全的类对象,转换为线程安全的类对象。具体方法为:synchronizedList、synchronizedSet、synchronizedMap。
3、实例代码
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class TestSingleton {
boolean lock ;
public boolean isLock() {
return lock;
}
public void setLock(boolean lock) {
this.lock = lock;
}
public static void main(String[] args) throws InterruptedException {
final Set<String> instanceSet = Collections.synchronizedSet(new HashSet<String>());
final TestSingleton lock = new TestSingleton();
lock.setLock(true);
ExecutorService executorService = Executors.newCachedThreadPool();
for (int i = 0; i < 100; i++) {
executorService.execute(new Runnable() {
public void run() {
while (true) {
if (!lock.isLock()) {
Singleton singleton = Singleton.getInstance();
instanceSet.add(singleton.toString());
break;
}
}
}
});
}
Thread.sleep(5000);
lock.setLock(false);
Thread.sleep(5000);
System.out.println("------并发情况下我们取到的实例------");
for (String instance : instanceSet) {
System.out.println(instance);
}
executorService.shutdown();
}
}
说明,实例代码转自:http://blog.csdn.net/zuoxiaolong8810/article/details/9005611