【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();
    }
}
相关推荐
java1234_小锋10 分钟前
Java高频面试题:SpringBoot为什么要禁止循环依赖?
java·开发语言·面试
铅笔侠_小龙虾16 分钟前
Flutter Demo
开发语言·javascript·flutter
2501_9445255425 分钟前
Flutter for OpenHarmony 个人理财管理App实战 - 账户详情页面
android·java·开发语言·前端·javascript·flutter
计算机学姐26 分钟前
基于SpringBoot的电影点评交流平台【协同过滤推荐算法+数据可视化统计】
java·vue.js·spring boot·spring·信息可视化·echarts·推荐算法
福大大架构师每日一题36 分钟前
ComfyUI v0.11.1正式发布:新增开发者专属节点支持、API节点强化、Python 3.14兼容性更新等全方位优化!
开发语言·python
wangdaoyin201037 分钟前
若依vue2前后端分离集成flowable
开发语言·前端·javascript
Filotimo_42 分钟前
Tomcat的概念
java·tomcat
索荣荣1 小时前
Java Session 全面指南:原理、应用与实践(含 Spring Boot 实战)
java·spring boot·后端
向阳开的夏天1 小时前
麒麟V10源码编译QT5.6.3 (x86 & arm64)
开发语言·qt