线程安全代码实例
import java.util.ArrayList;
public class Test5 {
public static void main(String[] args) throws InterruptedException {
ArrayList list = new ArrayList();
//为加锁 数据不安全
// for (int i = 0; i <= 100000; i++) {
// new Thread(()->{
// list.add(Thread.currentThread().getName());
// }).start();
// }
//加锁 数据安全
//每次新建一个线程 new Thread(()->{ 对原子数据(list)进行操作时,
//需要对给原子操作间加上synchronized同步代码块,保证数据安全。
//否则多个线程访问改原子数据(list集合的同一位置时),会进行覆盖。
for (int i = 0; i <= 100000; i++) {
new Thread(()->{
synchronized (list){
list.add(Thread.currentThread().getName());
}
}).start();
}
// for (int i = 0; i <= 1000; i++) {
// list.add(Thread.currentThread().getName());
// }
//这样就解决了Arrylist不安全问题,那么原来是什么呢?还有测试过程出现的问题
//至于为什么要睡2秒钟 防止主线层先执行
Thread.sleep(2000);
System.out.println(list.size());
}
}
这辈子坚持与不坚持都不可怕,怕的是独自走在坚持的道路上!!!