How to use shared memory on Java threads?

I am implementing a multi-threaded program in Java, where each thread is of type class Node extends Thread .

All of these classes generate specific values ​​that will be used by other classes.

It is easy for main to get values ​​from generated threads , but from threads itself, how can I get values ​​on other threads ?

 //Start the threads from a list of objects for (int i = 0; i < lnode.size(); i++) { lnode.get(i).start(); } 

thanks

+4
source share
4 answers

If there are threads of the same process / jvc instance, you do not need "shared memory", you only need a link for your data inside your protectors, for example, using a constructor or a static link. But you will need a synchronization / access control mechanism if more than one stream is written to this data.

+3
source

If you do something like:

 class MyThreadRunnable implements Runnable { List<String> strings; MyThreadRunnable(List<String> strings) { this.strings = strings; } public void run() { strings.add(getName()); } } // ... List<String> sharedStrings = new ArrayList<String>(); Thread t1 = new Thread(new MyThreadRunnable(sharedStrings)); Thread t2 = new Thread(new MyThreadRunnable(sharedStrings)); t1.start(); t2.start(); 

then both t1 and t2 (two different threads of the same type) will use the same list and see the changes made from another thread.

In fact, since I do not use synchronization for brevity, it is also possible that this can lead to incorrect list corruption and cause strange errors. I highly recommend that you investigate process synchronization and the java.util.concurrent package when working with concurrency.

+3
source

It sounds like you're looking for a ConcurrentHashMap , but without the details it's a little hard to say.

What data do you want to share between these streams and how should they be shared?

BTW - As a rule, it is better to implement Runnable than to expand Thread .

+1
source

You can use ThreadLocal to exchange variables. The following is the definition of ThreadLocal:

The Local stream can be considered as an access area, for example, a request for volume or a session. This is the flow area. You can install any object in the Local Stream, and this object will be global and local for the specific one that accesses this object.

More details here .

0
source

All Articles