Reputation: 131
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 m.n
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 m.n
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.
Upvotes: 1
Views: 174
Reputation: 9920
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));
}
}
}
}
}
Upvotes: 0
Reputation: 18148
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
Upvotes: 1