【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();
    }
}
相关推荐
only-qi1 小时前
146. LRU 缓存
java·算法·缓存
悟能不能悟1 小时前
js闭包问题
开发语言·前端·javascript
潼心1412o1 小时前
C语言(长期更新)第15讲 指针详解(五):习题实战
c语言·开发语言
xuxie132 小时前
SpringBoot文件下载(多文件以zip形式,单文件格式不变)
java·spring boot·后端
重生成为编程大王2 小时前
Java中的多态有什么用?
java·后端
Murphy_lx2 小时前
Lambda表达式
开发语言·c++
666和7772 小时前
Struts2 工作总结
java·数据库
中草药z2 小时前
【Stream API】高效简化集合处理
java·前端·javascript·stream·parallelstream·并行流
yangpipi-3 小时前
C++并发编程-23. 线程间切分任务的方法
开发语言·c++
野犬寒鸦3 小时前
力扣hot100:搜索二维矩阵 II(常见误区与高效解法详解)(240)
java·数据结构·算法·leetcode·面试