简体   繁体   中英

Share Variable between specific threads

I am facing a problem in java wherein my program makes n independent threads (of ClassA ) initially and then each thread of ClassA makes m dependent threads ( ClassB ). So in total I have now mn threads (of ClassB ). Now I want to share a variable between the m threads (of ClassB ) created by a specific thread of ClassA . I can't use static because then all the mn threads will share the same variable but I only want the m threads created by a specific thread of ClassA to share these. Is there any implementation I can follow to do the same?

Thanks.

You can pass the shared variable into B using its constructor

class B extends Thread {
    final private Object shared;

    B(Object obj) {
        shared = obj;
    }
}

Now have A pass the same object into each B that it creates

Here some working code that uses a mutable ArrayList as the shared value, each ClassB thread adds a 10 numbers to the list and then ends their execution.

import java.util.ArrayList;
import java.util.List;

public class FooMain {

    public static void main(String [] args) throws InterruptedException {
        FooMain f = new FooMain();
        ClassA a = f.new ClassA(10);
        a.start();
            // Give all the threads some time to finish.
        Thread.sleep(1000);
        for (String x : a.list) {
            System.out.println(x);
        }
        System.out.println(a.list.size());
    }

    public class ClassA extends Thread {
        public List<String> list;       
        private List<ClassB> threads;

        public ClassA(int m) {
            this.list = new ArrayList<>();
            this.threads = new ArrayList<>();
            for(int i = 0; i < m; i++) {
                this.threads.add(new ClassB(i, this.list));
            }
        }

        @Override
        public void run() {
            for (ClassB b : this.threads) {
                b.start();
            }
        }
    }

    public class ClassB extends Thread {
        private List<String> list;
        private int id;

        public ClassB(int id, List<String> list) {
            this.id = id;
            this.list = list;
        }

        @Override
        public void run() {
            for(int i = 0; i < 10; i++) {
                synchronized(this.list) {
                    this.list.add("Id:" + Integer.toString(this.id) + " - #: " + Integer.toString(i));
                }
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM