如何在Java线程上使用共享内存? [英] How to use shared memory on Java threads?

查看:339
本文介绍了如何在Java线程上使用共享内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用Java实现一个多线程程序,其中每个thread的类型都是class Node extends Thread.

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

所有这些类都会生成某些值,这些值将由其他类使用.

All these classes generate certain values which will be used by other classes.

对于main,从生成的threads中获取值很容易,但是从threads本身内部,如何获得其他threads上的值?

For main it's easy to get the values from the generated threads, but from within threads itself, how can I get the values on other threads?

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

谢谢

推荐答案

如果您执行以下操作:

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();

然后t1t2(相同类型的两个不同线程)将使用相同的列表,并查看对另一个线程所做的更改.

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.

实际上,由于我没有为了简洁起见使用任何同步,因此也有可能以某种无法预测的方式破坏列表并导致奇怪的错误.我强烈建议您研究进程同步以及使用并发时的java.util.concurrent程序包.

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.

这篇关于如何在Java线程上使用共享内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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