有必要用一个线程添加和另一读队列中的挥发性标志? [英] Is the volatile mark necessary for a queue with one thread adding and another reading?

查看:119
本文介绍了有必要用一个线程添加和另一读队列中的挥发性标志?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

响应于<一个一些意见href=\"http://stackoverflow.com/questions/11847092/android-tcp-does-not-flush-until-socket-is-closed#comment15763190_11847092\">this螺纹,我想知道如果做一个队列中,将有一个线程将它和另一个线程从中读取需要'挥发'标志?

in response to some comments in this thread, I am wondering if making a queue that will have one thread adding to it and another thread reading from it requires the 'volatile' mark?

我想,大多数情况下是正常的,但在阅读和写作的大小的队列中的情况下,1可能导致的问题,没有它?

I suppose most cases would be alright, but in the case of reading and writing in a queue of size 1 could cause issues without it?

目标:


  • 一个线程安全的队列在那里我可以发布消息将通过TCP套接字连接发送。该出流将通过另一个阶级谁将会检查队列为空,在每个循环的开始
  • 管理

我的想法/思考:


  • 也许有一个内置的队列,我没有在我的研究中发现TCP套接字?

  • 是挥发性的良好在这种情况下使用,或者我应该用封堵或者锁闭电话?

先谢谢了。

推荐答案

使用锁定的对象,如果你想同步访问,就像你提到的。

Use lock objects if you want synchronized access like you've mentioned.

挥发性是不是真的在这方面使用。声明你的列表myList中对象为volatile意味着,如果你曾经试图实例化一个新的对象,并将其设置为myList中的变量,那么线程将得到保证,知道有是分配给它的(大约)的新对象。它不会阻止或同步任何与实际的对象。

Volatile is not really used in this context. Declaring your List myList object as volatile would mean that if you ever tried to instantiate a new Object and set it to the myList variable, then the thread would be guaranteed to know that there is a new object assigned to it (roughly). It doesn't block or synchronize anything to do with the actual object.

基本上,就像你说的,你需要确保当您读取或写入到列表中,没有什么会搞乱名单,并导致意外的错误。从在同一时间发生停止两个事物,用锁对象和Java synchronized关键字<击>,或使用已可以同步读/写你一个列表类型。

Basically, like you said, you need to be sure that when you are reading or writing to the list, that nothing will mess the list up and cause an unexpected error. For stopping two things from happening at the same time, use lock objects and the Java synchronized keyword, or use a List type that already synchronizes read/writes for you.

这篇关于有必要用一个线程添加和另一读队列中的挥发性标志?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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