Lui*_*s S 5 java multithreading class shared-memory multiprocessing
我正在用Java实现一个多线程程序,每个程序thread都是一个type class Node extends Thread。
所有这些类都会生成某些值,这些值将由其他类使用。
因为main很容易从生成的值中获取值threads,但是从threads自身内部获取值,我又该如何获取其他值threads?
//Start the threads from a list of objects
for (int i = 0; i < lnode.size(); i++) { 
    lnode.get(i).start();
}
Run Code Online (Sandbox Code Playgroud)
谢谢
如果您执行以下操作:
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();
Run Code Online (Sandbox Code Playgroud)
然后两者t1和t2(相同类型的两个不同线程)将使用相同的列表,并查看其他线程对其所做的更改。
实际上,由于为简洁起见,我没有使用任何同步,因此这也可能会以某种不可预测的方式破坏列表并导致奇怪的错误。我强烈建议您java.util.concurrent在处理并发时研究进程同步和包。