【Java并发编程六】多线程越界问题

ArrayList()越界错误

java 复制代码
import java.util.ArrayList;
public class myTest implements Runnable {
    static ArrayList<Integer> a = new ArrayList<>(10);
    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(new myTest());
        Thread t2 = new Thread(new myTest());
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println(a.size());
    }
    @Override
    public void run() {
        for(int i=0; i<10000; i++) {
            a.add(i);
        }
    }
}

上面的代码会有三种可能的运行结果:

①越界。因为List的add方法会先检查list是否足够,从而选择扩容,若第一个线程刚刚扩容完毕,还未添加,第二个线程就进行了检查,从而导致list越界。

②正常结果。结果为20000。

③异常结果。这是因为两个线程同时对i的值进行修改。

HashMap

HashMap也会出现上述情况。

解决措施

使用synchronized修饰方法。

java 复制代码
import java.util.ArrayList;
public class myTest implements Runnable {
    static ArrayList<Integer> a = new ArrayList<>(10);
    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(new myTest());
        Thread t2 = new Thread(new myTest());
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println(a.size());
    }
    public static synchronized void func() {
        for(int i=0; i<10000; i++) {
            a.add(i);
        }
    }
    @Override
    public void run() {
        func();
    }
}
相关推荐
quikai19811 天前
python练习第六组
java·前端·python
222you1 天前
线程的常用方法
java·开发语言
云栖梦泽1 天前
易语言界面美化与组件扩展
开发语言
catchadmin1 天前
PHP 值对象实战指南:避免原始类型偏执
android·开发语言·php
Trouville011 天前
Python中encode和decode的用法详解
开发语言·python
是梦终空1 天前
JAVA毕业设计259—基于Java+Springboot+vue3工单管理系统的设计与实现(源代码+数据库+开题报告)
java·spring boot·vue·毕业设计·课程设计·工单管理系统·源代码
JS_GGbond1 天前
JavaScript事件循环:餐厅里的“宏任务”与“微任务”
开发语言·javascript·ecmascript
用户2190326527351 天前
Spring Boot 集成 Redis 实现看门狗 Lua 脚本分布式锁
java·后端
zybsjn1 天前
ShardingSphere 启动报错 “Unknown table ‘keywords‘ in information_schema“ 完整解决方案
java
月明长歌1 天前
【码道初阶】【LeetCode 102】二叉树层序遍历:如何利用队列实现“一层一层切蛋糕”?
java·数据结构·算法·leetcode·职场和发展·队列