简体   繁体   English

Java同步集合与对象

[英]Java Synchronized Collections vs Object

I'm wondering what the difference is between these ways of synchronization 我想知道这些同步方式之间有什么区别

List<Integer> intList = Collections.synchronizedList(new ArrayList<Integer>());

synchronized (intList) {
    //Stuff
}

and using an object lock 并使用对象锁

Object objectLock = new Object();

List<Integer> intList = new ArrayList<Integer>();

synchronized (objectLock) {
    //Stuff
}

The first approach makes sure that individual method calls are synchronized, and it avoids needing to manage a separate lock object. 第一种方法确保单个方法调用是同步的,并且避免了需要管理单独的锁对象。 One thread can call 一个线程可以调用

intList.add(3);

and another can call 另一个可以打电话

intList.clear();

without a synchronized block, and it'll be properly synchronized. 没有synchronized块,它将被正确同步。 (Unfortunately, this doesn't help when you need to hold the lock for a group of function calls; then, you need a synchronized block around those calls.) Also, if you need to pass the list around, you can use (不幸的是,当您需要为一组函数调用保持锁定时,这无济于事;然后,在这些调用周围需要一个synchronized块。)此外,如果您需要传递列表,则可以使用

otherObject.doStuffWith(intList);

and

return intList;

instead of 代替

otherObject.doStuffWith(intList, objectLock);

and

return ListAndLock(intList, objectLock);

The code you show is not necessarily thread safe yet!! 您显示的代码不一定是线程安全的!!

The only difference between one excerpt and the other is the object you use as a monitor for synchronization. 一个摘录和另一个摘录之间的唯一区别是用作同步监视器的对象。 This difference will determine which object should be used for synchronization by other threads that need access to the mutable data you're trying to protect 这种差异将确定需要访问您要保护的可变数据的其他线程应使用哪个对象进行同步

great read for this: java concurrency in practice 很好的阅读: 实践中的Java并发

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM