简体   繁体   English

使用ExecutorService时,线程安全内的类是否安全?

[英]When using ExecutorService, are the classes within threadsafe?

I have an implementation of a Runnable class which contains a Vector of objects that items are removed from one by one and processed. 我有一个Runnable类的实现,该类包含一个Vector对象,这些对象被逐个删除并处理。

Using the ExecutorService and creating a newFixedThreadPool with n number of threads, are there n number of instances of the Runnable class? 使用ExecutorService并使用n个线程创建一个newFixedThreadPool,是否存在n个Runnable类的实例? If so, are the classes and the Vector within threadsafe, or would this need to be implemented using synchronized? 如果是这样,那么线程安全中的类和Vector是安全的还是需要使用同步实现?

Thanks 谢谢

You are using newFixedThreadPool so it means, at any point max n threads are active. 您正在使用newFixedThreadPool ,这意味着在任何时候最多n线程处于活动状态。 If you start n Runnables and all threads are busy, every additional Runnable will wait until a thread is available. 如果启动n Runnable,并且所有线程都忙,则每个其他Runnable将等待,直到有一个线程可用为止。

Your implementation has no shared resources (at least it looks like so) between runnables. 您的实现在可运行对象之间没有共享资源(至少看起来像这样)。 In this case you don't need synchronization. 在这种情况下,您不需要同步。 But if, for example, you have one instance of vector and multiple instances of your 'workers', in that case you need synchronization. 但是,例如,如果您有一个vector实例和多个“ workers”实例,那么在这种情况下,您需要进行同步。

As others have stated, if you are sharing your Vector across Runnables, then it is not threadsafe. 正如其他人所说,如果您要在Runnable中共享Vector,那么它不是线程安全的。 To be threadsafe, you should use either bound queue (like BlockingQueue) or unbound queue (like ConcurrentLinkedQueue) instead of Vector. 为了保持线程安全,您应该使用绑定队列(例如BlockingQueue)或非绑定队列(例如ConcurrentLinkedQueue)而不是Vector。

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

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