How to use shared memory on Java threads?

。_饼干妹妹 提交于 2019-12-05 10:40:45

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 be using the same list, and see changes to it made from the other thread.

Actually, since I'm not using any synchronisation for brevity, it's also possible this would corrupt the list in some unpredictable way and cause weird errors. I strongly encourage you investigate process synchronisation, and the java.util.concurrent package when working with concurrency.

If are threads of the same process/jvc instance you will not need "shared memory", you only need a reference for your data inside your treads, for example via constructor or static reference. But you will need a synchronization / control access mechanism if more than one thread writes on that data.

It sounds like you are looking for a ConcurrentHashMap but without a little more detail it is difficult to tell.

What kind of data are you hoping to share between these threads and how will they need to share it?

BTW - It is generally considered better to implement Runnable than to extend Thread.

You can use ThreadLocal to share variables. The definition of ThreadLocal is shown below :

Thread Local can be considered as a scope of access, like a request scope or session scope. It’s a thread scope. You can set any object in Thread Local and this object will be global and local to the specific thread which is accessing this object.

You can find more information here.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!