一、验证Collections.synchronizedList();线程保护机制
1.创建一个单例//首次运行完、切换a方法中受线程保护和不受线程的代码
/**
*
* 被调用的类
* @author Ali
*
*/
class A {
//单例模式
private static A a = new A();
//隐藏实例
private A() {};
//返回当前 实例
public static A getA(){
return a;
}
static List<String> list1 = new ArrayList<String>();
static List<String> list_synchronizedList =Collections.synchronizedList(new ArrayList<String>());
public static void a(String a) {
//线程不受保护的可能会抛出异常
for (int i = 0; i < 50; i++) {
//往list1中添加元素
list1.add(""+i);
}
//输出该数组
System.out.println("list1"+list1);
//线程受保护的不会报异常
// for (int i = 0; i < 50; i++) {
//往list_synchronizedList中添加元素
// list_synchronizedList.add(""+i);
// }
// System.out.println("list_synchronizedList"+list_synchronizedList);
}
}
2.开辟一个新线程,并调用单例中的a方法
/**
*
* 开线程(实现异步)
* @author Ali
*
*/
class PaintThread extends Thread {
@Override
public void run() {
A a = A.getA();
a.a("PaintThread");
}
}
3.在主线程中调用a方法和新线程
public class YanZhengJiHeXianChengBaoHu {
public static void main(String[] args) throws InterruptedException {
PaintThread paintThread =new PaintThread();
//线程使用方法1
new PaintThread().start();
A a = A.getA();
a.a("main");
}
}
4.1当a方法中使用不受线程保护的list1时,
可能会抛出ConcurrentModificationException(并发修改异常)
4.2 当a方法中使用不受线程保护的list1并且如下图所示时,
public static void a(String a) {
//线程不受保护的可能会抛出异常
for (int i = 0; i < 50; i++) {
list1.add(""+i);
}
}
、
可能会抛出ArrayIndexOutOfBoundsException(数组索引越界异常)
4.3 当a方法中使用受线程保护的list_synchronizedList时,不会出现以上异常。
5. 不使用线程保护和使用线程保护之间的速度对比
(1)两者(受保护与不受保护)都开三个线程
(2)不受保护不报异常
(3)a方法中的for循环运行500000次
在满足上面三者条件的情况下:
5.1 获取不受线程保护需要的时间:
a方法代码如下:
public static void a(String a) {
long date1 = System.currentTimeMillis();
//线程不受保护的可能会抛出异常
for (int i = 0; i < 500000; i++) {
list1.add(""+i);
}
long date2 = System.currentTimeMillis();
System.out.println(date2-date1);//平均70ms
}
运行完时间约为70ms
5.2 获取受线程保护需要的时间:
a方法代码如下:
public static void a(String a) {
long date3 = System.currentTimeMillis();
//线程受保护的不会报异常
for (int i = 0; i < 500000; i++) {
list_synchronizedList.add(""+i);
}
long date4 = System.currentTimeMillis();
System.out.println(date4-date3);//平均120ms
}