List中Collections.synchronizedList和synchronized

1. 一个简单的例子
public class MultiThread {
    
    public static final List<Long> list  = Collections.synchronizedList(new ArrayList<Long>());
    
    public static void main(String[] args) {
        for(int i = 1;i<=100;i++){
            list.add(Long.valueOf(i));
        }
        
        MyThread myThread = new MultiThread().new MyThread(); 
        Thread t1 = new Thread(myThread); 
        t1.setName("线程1"); 
        t1.start(); 

        Thread t2 = new Thread(myThread); 
        t2.setName("线程2"); 
        t2.start(); 

        Thread t3 = new Thread(myThread); 
        t3.setName("线程3"); 
        t3.start();  
    }
    
    
    public class MyThread implements Runnable{

        @Override
        public void run() {
            for(int i = 0;i<list.size();i++){
                // 同步list,打印数据并删除该数据 
                synchronized (list) {
                    try {
                        Thread.sleep(100);
                    } catch (Exception e) {
                    }
                    System.out.print(Thread.currentThread().getName() + ":" + list.get(i)+"\n");
                    list.remove(i);
                }
            }
        }
        
    }
}

2. Collections.synchronizedList保证了, ArrayLIst的add. get等操作时, 有锁. 
但是这种情况下, 不能保证线程同步.
if(!list.size() > 0) {  
    list.remove(0); 
}  
isEmpty之后, 其他线程进行了list数据操作, 那么此时的get对应的list已经改变. 那么就需要使用synchronized
synchronized(list) {  
     if(!list.isEmpty()) {  
        list.remove(0); 
} }

实际上使用sybchronized是为了此此操作的原子性.




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值