比这篇新的文章: Java中Exception的三种类型
比这篇旧的文章: 发芽网根目录的.htaccess

ArrayList的线程安全与不安全对比演示

语言: Java, 标签: safe list collection thread 2009/02/26发布 1年前更新
作者: Programus, 点击635次, 评论(0), 收藏者(0), , 打分:

背景
主题: 字体:
01 import java.util.ArrayList;
02 import java.util.Collections;
03 import java.util.List;
04 import java.util.Random;
05
06 public class ThreadSafeDemo {
07     public static int demo(final List list, final int testCount) throws InterruptedException {
08         ThreadGroup group = new ThreadGroup(list.getClass().getName() + "@" + list.hashCode());
09         final Random rand = new Random();
10        
11         Runnable listAppender = new Runnable() {
12             public void run() {
13                 try {
14                     Thread.sleep(rand.nextInt(2));
15                 } catch (InterruptedException e) {
16                     return;
17                 }
18                 list.add("0");
19             }
20         };
21        
22         for (int i = 0; i < testCount; i++) {
23             new Thread(group, listAppender, "InsertList-" + i).start();
24         }
25        
26         while (group.activeCount() > 0) {
27             Thread.sleep(10);
28         }
29        
30         return list.size();
31     }
32     public static void main(String[] args) throws InterruptedException {
33         List unsafeList = new ArrayList();
34         List safeList = Collections.synchronizedList(new ArrayList());
35         final int N = 10000;
36         for (int i = 0; i < 10; i++) {
37             unsafeList.clear();
38             safeList.clear();
39             int unsafeSize = demo(unsafeList, N);
40             int safeSize = demo(safeList, N);
41             System.out.println("unsafe/safe: " + unsafeSize + "/" + safeSize);
42         }
43     }
44 }


所有评论,共0条:( 我也来说两句)


发表评论

注册登录后再发表评论