简体   繁体   English

java - 在线程之间共享数据 - 原子引用或同步

[英]java - sharing data between threads - atomicreference or synchronize

I am making a 2 player videogame, and the oponent's position gets updated on a thread, because it has a socket that is continuously listening. 我正在制作一个2人的视频游戏,并且对手的位置在一个线程上得到更新,因为它有一个持续监听的套接字。 What I want to share is position and rotation. 我想分享的是位置和轮换。

As it is a videogame I don't want the main thread to be blocked (or be just the minimum time possible) and I don't want the performance to be affected. 由于它是一个视频游戏,我不希望主线程被阻止(或者只是最短的时间),我不希望性能受到影响。 So from what I've seen to share this info the normal thing to do would be something like 因此,从我所看到的分享这些信息,正常的事情将是这样的

class sharedinfo
{
   public synchronized read();
   public synchronized write();
}

but this would block the read in the main thread (the same that draws the videogame) until the three values (or even more info in the future are written) are written, and also I've read that synchronized is very expensive (also it is important to say this game is for android also, so performance is very important). 但是这会阻止主线程中的读取(绘制视频游戏的相同),直到写入三个值(或者将来写入更多信息),并且我还读到同步非常昂贵(也是它)重要的是说这个游戏也适用于Android,因此性能非常重要)。

But I was thinking that maybe having sharedInfo inside an AtomicReference and eliminating synchronized would make it more efficient, because it would only stop when the reference itself is being updated (the write would not exist, I would create a new object and put it on the atomicreference), also they say that atomic* use hardware operations and are more efficient than synchronized. 但我想可能在AtomicReference中使用sharedInfo并消除synchronized会使它更有效率,因为它只会在引用本身被更新时停止(写入不存在,我会创建一个新对象并将其放在原子引用),他们也说原子*使用硬件操作并且比同步更有效。

What do you think? 你怎么看?

Consider using a queue for this, Java has some nice concurrent queue implementations. 考虑使用队列,Java有一些很好的并发队列实现。 Look up the BlockingQueue interface in java.util.concurrent, and who implements it. 在java.util.concurrent中查找BlockingQueue接口,以及实现它的人。 Chances are you fill find strategies implemented that you hadn't even considered. 你有机会填写你甚至没有考虑过的实施策略。

Before you know it, you will want to communicate more than just positions between your threads, and with a queue you can stick different type of objects in there, maybe at different priorities, etc. 在你知道之前,你需要传达的不仅仅是线程之间的位置,而是通过队列,你可以在那里粘贴不同类型的对象,可能有不同的优先级等。

If in your code you use Interfaces (like Queue or BlockingQueue) as much as possible (ie anywhere but the place where the specific instance is constructed), it is really easy to swap out what exact type of Queue you are using, if you need different functionality, or just want to play around. 如果你的代码中尽可能多地使用接口(比如Queue或BlockingQueue)(即除了构造特定实例的地方之外的任何地方),如果你需要,很容易换出你正在使用的确切类型的Queue不同的功能,或只是想玩。

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

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