同步列表如何工作? [英] How do Synchronized Lists Work?

查看:45
本文介绍了同步列表如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定我是否理解 Java 中的同步列表.假设我有以下内容:

I am not sure I understand Synchronized Lists in Java. Suppose I have the following:

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

 // Assumption: This is running on a separate thread
 public void add() {
      numbers.add(new Random().nextInt(100));
 }

 // This is also running on a separate thread
 public void doSomething() {
      synchronized(numbers) {
           for (int i : numbers) {}
      }
 }

基本上,如果 doSomething() 被调用,add() 是否能够将数字添加到列表中?如果我改为使用 public synchronized void add()public synchronized void doSomething() 会发生什么?

Basically, will the add() be able to add numbers to the list if doSomething() is invoked? What would happen if I instead used public synchronized void add() and public synchronized void doSomething()?

我正在开发 UDP 套接字服务器,我打算将客户端存储在 ArrayList 中.我会有多个线程可以读取、写入和修改此列表.我该怎么办?

I am working on a UDP Socket Server, and I was going to store clients in an ArrayList. I would have multiple threads that can read, write, and modify this list. What should I be doing?

推荐答案

如果调用 doSomething(),add() 是否能够将数字添加到列表中?

will the add() be able to add numbers to the list if doSomething() is invoked?

不,直到调用 doSomething() 的线程离开同步块.

No, not until the thread invoking doSomething() leaves the synchronized block.

如果我改为使用 public synchronized void add() 和 public synchronized void doSomething() 会发生什么?

What would happen if I instead used public synchronized void add() and public synchronized void doSomething()?

假设这些是唯一使用列表的地方,效果是一样的.但是您会在包含列表的对象上进行同步,而不是在列表本身上进行同步.

Assuming these are the only places where the list is used, the effect would be the same. But you would syncronize on the object containing the list rather than synchronizing on the list itself.

基本上,对共享状态的所有访问都必须在同一个锁上同步.您选择您喜欢的锁.您可以使用像 CopyOnWriteArrayList 这样的并发集合,而不是使用同步列表或同步方法.

Basically, all the accesses to a shared state must be synchronized on the same lock. You choose the lock that you prefer. Instead of using a sychronized list, or synchronized methods, you could use a concurrent collection like a CopyOnWriteArrayList.

这篇关于同步列表如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆