且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在线程之间共享数据

更新时间:2022-10-15 12:21:10

Concurrent execution in Java generally rely on "shared memory" so just make sure the code in the two threads share a reference to a common data structure in which they can exchange information.

All you need to make sure is that the access to this structure is done in a synchronized / thread safe manner. This can be done manually by using the synchronized keyword (not recommended) or by using classes from the java.util.concurrent package (recommended).

A BlockingQueue would probably suit you well. What problems did you have when you tried this class?

The thing is that the thread that reads from the BlockingQueue needs to differentiate between the data that is written in the BlockingQ(data that comes from user1,2,3...).

I suggest you create a class for UserData which contains both the data and which user it came from. (And store it in a BlockingQueue<UserData>.)

How long and how much data can a BlockingQ keep????Because all this data needs to be stored in a DB in my second app...so I can afford losing any of it!!!!!!!!!!!

The BlockingQueue is actually an interface, but all standard implementations of it (ArrayBlockingQueue, LinkedBlockingQueue...) can all keep an arbitrary ammount of data (i.e., are limited only by the ammount of free memory on your computer).