黑马程序员技术交流社区

标题: Collections里的synchronizedxxxxxxx()方法 [打印本页]

作者: 贾振凯    时间: 2013-3-26 20:32
标题: Collections里的synchronizedxxxxxxx()方法
本帖最后由 贾振凯 于 2013-3-27 20:16 编辑


Collections里面的这些synchronized打头的方法返回的
都是相应集合类的支持同步的线程安全的版本
可为什么API上说:
synchronized(collection) {
      Iterator i = collection.iterator(); // Must be in the synchronized block
      while (i.hasNext())
          foo(i.next());
  }
要迭代还是必须放在同步代码块中!


这上下两个同步怎么个关系,,,,懵!!

作者: 张东贤    时间: 2013-3-26 20:45
e ...要我说呢

要同步。做好用vector,

还有hashtable

你觉得呢
作者: 张东贤    时间: 2013-3-26 20:46
轻量级的东东不靠谱


原子性什么的,最好别用
作者: itserious    时间: 2013-3-26 20:54

你确定你没有用错吗?
看看我写的吧!

package test;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;


public class RegServer  {
        public static void main(String[] args) {
                //定义一个线程不安全的集合。
                List<Integer> coll=new ArrayList<Integer>();
                //添加元素。
                        coll.add(111);
                        coll.add(222);
                        coll.add(333);
                       
                        //将一个不线程不安全的集合转成一个安全的集合。
                List <Integer> list=Collections.synchronizedList(coll);
                //迭代集合
                        Iterator<Integer> it=list.iterator();
                       
                        //遍历集合。
                        while(it.hasNext()){
                                //取出元素。
                                Integer val=it.next();
                                //打印元素。
                                System.out.println(val);
                        }
        }
}
//运行结果:
/*
111
222
333
*/

作者: 贾振凯    时间: 2013-3-26 21:20
itserious 发表于 2013-3-26 20:54
你确定你没有用错吗?
看看我写的吧!

呃.............我下边那段小代码是API上的,不理解怎么回事儿........................




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2