java向量和线程安全

问题描述:

我想知道这段代码是否会造成麻烦:

I'm wondering if this code will do any trouble:

我有一个向量在许多线程之间共享.每次线程必须从向量中添加/删除内容时,我都会在synchronized块下执行此操作.但是,主线程有一个调用:

I have a vector that is shared among many threads. Every time a thread has to add/remove stuff from the vector I do it under a synchronized block. However, the main thread has a call:

System.out.println("the vector's size: "+ vec.size());

不是synchronized.

这会引起麻烦吗?

我假设您是指java.util.Vector.

实际上Vector.size() 是同步的,并且将返回与向量状态一致的值(当调用size()的线程进入监视器时.)如果返回42,则在某个时间点向量正好包含42个元素.

Actually Vector.size() is synchronized and will return a value consistent with the vector's state (when the thread calling size() enters the monitor.) If it returns 42, then at some point in time the vector contained exactly 42 elements.

如果您要在另一个线程的循环中添加项目,则无法预测确切的大小,但出于监视目的应该是正确的.

If you're adding items in a loop in another thread then you cannot predict the exact size, but it should be fine for monitoring purposes.