ArrayList()越界错误
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());}@Overridepublic void run() {for(int i=0; i<10000; i++) {a.add(i);}}
}
上面的代码会有三种可能的运行结果:
①越界。因为List的add方法会先检查list是否足够,从而选择扩容,若第一个线程刚刚扩容完毕,还未添加,第二个线程就进行了检查,从而导致list越界。
②正常结果。结果为20000。
③异常结果。这是因为两个线程同时对i的值进行修改。
HashMap
HashMap也会出现上述情况。
解决措施
使用synchronized修饰方法。
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);}}@Overridepublic void run() {func();}
}