1.arraylist为ä»ä¹çº¿ç¨ä¸å®å
¨
arraylist为ä»ä¹çº¿ç¨ä¸å®å ¨
é¦å 说ä¸ä¸ä»ä¹æ¯çº¿ç¨ä¸å®å ¨ï¼çº¿ç¨å®å ¨å°±æ¯å¤çº¿ç¨è®¿é®æ¶ï¼éç¨äºå éæºå¶ï¼å½ä¸ä¸ªçº¿ç¨è®¿é®è¯¥ç±»çæ个æ°æ®æ¶ï¼è¿è¡ä¿æ¤ï¼å ¶ä»çº¿ç¨ä¸è½è¿è¡è®¿é®ç´å°è¯¥çº¿ç¨è¯»åå®ï¼å ¶ä»çº¿ç¨æå¯ä½¿ç¨ãä¸ä¼åºç°æ°æ®ä¸ä¸è´æè æ°æ®æ±¡æã线ç¨ä¸å®å ¨å°±æ¯ä¸æä¾æ°æ®è®¿é®ä¿æ¤ï¼æå¯è½åºç°å¤ä¸ªçº¿ç¨å åæ´æ¹æ°æ®é ææå¾å°çæ°æ®æ¯èæ°æ®ã å¦å¾ï¼Listæ¥å£ä¸é¢æ两个å®ç°ï¼ä¸ä¸ªæ¯ArrayListï¼å¦å¤ä¸ä¸ªæ¯vectorã ä»æºç çè§åº¦æ¥çï¼å 为Vectorçæ¹æ³åå äºï¼synchronized å ³é®åï¼ä¹å°±æ¯åæ¥çææï¼sunå ¬å¸å¸æVectoræ¯çº¿ç¨å®å ¨çï¼èå¸æarraylistæ¯é«æçï¼ç¼ºç¹å°±æ¯å¦å¤çä¼ç¹ã 说ä¸åçï¼ç¾åº¦çï¼å¾å¥½ç解ï¼ï¼ ä¸ä¸ª ArrayList ï¼å¨æ·»å ä¸ä¸ªå ç´ çæ¶åï¼å®å¯è½ä¼æ两æ¥æ¥å®æï¼
1. å¨ Items[Size] çä½ç½®åæ¾æ¤å ç´ ï¼
2. å¢å¤§ Size çå¼ã
å¨å线ç¨è¿è¡çæ åµä¸ï¼å¦æ Size = 0ï¼æ·»å ä¸ä¸ªå ç´ åï¼æ¤å ç´ å¨ä½ç½® 0ï¼èä¸ Size=1ï¼
èå¦ææ¯å¨å¤çº¿ç¨æ åµä¸ï¼æ¯å¦æ两个线ç¨ï¼çº¿ç¨ A å å°å ç´ åæ¾å¨ä½ç½® 0ãä½æ¯æ¤æ¶ CPU è°åº¦çº¿ç¨Aæåï¼çº¿ç¨ B å¾å°è¿è¡çæºä¼ã线ç¨Bä¹åæ¤ ArrayList æ·»å å ç´ ï¼å 为æ¤æ¶ Size ä»ç¶çäº 0 ï¼æ³¨æå¦ï¼æ们å设çæ¯æ·»å ä¸ä¸ªå ç´ æ¯è¦ä¸¤ä¸ªæ¥éª¤å¦ï¼è线ç¨Aä» ä» å®æäºæ¥éª¤1ï¼ï¼æ以线ç¨Bä¹å°å ç´ åæ¾å¨ä½ç½®0ãç¶å线ç¨Aå线ç¨Bé½ç»§ç»è¿è¡ï¼é½å¢å Size çå¼ã
é£å¥½ï¼ç°å¨æ们æ¥çç ArrayList çæ åµï¼å ç´ å®é ä¸åªæä¸ä¸ªï¼åæ¾å¨ä½ç½® 0ï¼è Size å´çäº 2ãè¿å°±æ¯â线ç¨ä¸å®å ¨âäºã
示ä¾ç¨åºï¼
package test;
import java.util.ArrayList;
import java.util.List;
public class ArrayListInThread implements Runnable {
List<String> list1 = new ArrayList<String>();// not thread safe
// List<String> list1 = Collections.synchronizedList(new ArrayList<String>());// thread safe
public void run() {
try {
Thread.sleep((int)(Math.random() * 2));
}
catch (InterruptedException e) {
e.printStackTrace();
}
list1.add(Thread.currentThread().getName());
}
public static void main(String[] args) throws InterruptedException {
ThreadGroup group = new ThreadGroup("mygroup");
ArrayListInThread t = new ArrayListInThread();
for (int i = 0; i < ; i++) {
Thread th = new Thread(group,源码gitee怎么下载源码 t, String.valueOf(i));
th.start();
}
while (group.activeCount() > 0) {
Thread.sleep();
}
System.out.println();
System.out.println(t.list1.size()); // it should be if thread safe collection is used.
}
}